if statement not working

12 ビュー (過去 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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by