if statement not working

11 次查看(过去 30 天)
If the Xnew is negative the answer for X should also be negative, but this is not the case. The Y does work correctly however. I included the input array, the r is constantly 13.
function [X,Y,Z] = bolcoordinaten2(Xnew,Ynew,r)
Z = r-cos(2*atan((abs(sqrt((Xnew.^2)+(Ynew.^2))))./(2*r))).*r;
a = cos(atan(Ynew./Xnew)).*r.*sin(2*atan((abs(sqrt((Xnew.^2)+(Ynew.^2))))./(2*r)));
if Xnew < 0
X = a*(-1);
else
X = a;
end
b = sin(atan(Ynew./Xnew)).*r.*sin(2*atan((abs(sqrt((Xnew.^2)+(Ynew.^2))))./(2*r)));
if Ynew < 0
Y = b*(-1);
else
Y= b;
end
end

采纳的回答

Walter Roberson
Walter Roberson 2018-1-8
mask = XNew < 0;
X = a;
X(mask) = -X(mask);

更多回答(1 个)

Jan
Jan 2018-1-8
编辑:Jan 2018-1-8
"If the Xnew is negative the answer for X should also be negative"
As code considering that a could be negative also:
if Xnew < 0
X = -abs(a);
else
X = a;
end
Do you want that X is positive, if Xnew is positive also? Then:
else
X = abs(a);
end
Alternatively without IF:
X = sign(Xnew) * abs(a);
But this would set X to 0 if Xnew is 0.
The code can be accelerated by avoiding repeated calculations:
function [X,Y,Z] = bolcoordinaten2(Xnew,Ynew,r)
c = atan(abs(sqrt(Xnew.^2 + Ynew.^2)) ./ r);
d = atan(Ynew ./ Xnew);
Z = r - cos(c) .* r;
X = cos(d) .* r .* sin(c);
if Xnew < 0
X = -abs(X);
end
Y = sin(d) .* r .* sin(c);
if Ynew < 0
Y = -abs(Y);
end
end
[EDITED] Ah, your inputs are vectors. I cannot run Matlab currently, such that I do not know what's in the attached MAT file. Please note that "does not work" is not useful to describe a problem. Better explain what you get and what you want instead.
For vectors use logical indexing:
X = abs(cos(d) .* r .* sin(c)); % Or without abs()?
negX = (Xnew < 0);
X(negX) = -X(negX);
Your code might work for Y, because of the sign of sin() in the applied range. But for other input values the shown method might fail also.
  4 个评论
Bodille Blomaard
Bodille Blomaard 2018-1-8
Yes indeed, I want to look at the individual members. I just don't understand why it doe work for the Y.
Jan
Jan 2018-1-8
编辑:Jan 2018-1-8
Ah, the inputs are vectors. See [EDITED].
You can find out what happens if you use the debugger: https://www.mathworks.com/help/matlab/matlab_prog/debugging-process-and-features.html. Note that if Xnew < 0 is executed as if all(Xnew < 0) internally. If XNew has different signs, this will not do, what you expect.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by