if statement not working

조회 수: 13 (최근 30일)
Bodille Blomaard
Bodille Blomaard 2018년 1월 8일
댓글: Bodille Blomaard 2018년 1월 8일
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
Bodille Blomaard
Bodille Blomaard 2018년 1월 8일
Thank you!! it worked!

댓글을 달려면 로그인하십시오.

추가 답변 (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