if statement not working

11 views (last 30 days)
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

Accepted Answer

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

More Answers (1)

Jan
Jan on 8 Jan 2018
Edited: Jan on 8 Jan 2018
"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 Comments
Bodille Blomaard
Bodille Blomaard on 8 Jan 2018
Yes indeed, I want to look at the individual members. I just don't understand why it doe work for the Y.
Jan
Jan on 8 Jan 2018
Edited: Jan on 8 Jan 2018
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.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!