How do I write an if loop in a nested for loop

11 ビュー (過去 30 日間)
Walker Boldman
Walker Boldman 2020 年 5 月 13 日
コメント済み: Rik 2020 年 5 月 13 日
I am trying to create a list of instances where x is equal to y, where x and y are created by a nested for loop. However, the if statement seems to only run through the first iteration of the loop.
radiusincrement = 1;
thetaincrement = 45;
k=1;
for i=1:1:5/radiusincrement %two for loops that will sweep through wafer points
for j=1:1:thetatotal
r(i,j) = (i-1)*radiusincrement;
theta(i,j) = (j-1)*thetaincrement;
x(i,j) = r(i,j).*cos(theta(i,j).*pi/180);
y(i,j) = r(i,j).*sin(theta(i,j).*pi/180);
point = [x(i,j) y(i,j) 0];
if point(1)==point(2)
kx(k)=x(i,j);
ky(k)=y(i,j);
k=k+1;
end
end
end
What am I doing wrong? Thanks!

採用された回答

Rik
Rik 2020 年 5 月 13 日
編集済み: Rik 2020 年 5 月 13 日
Welcome to the world of floats. Just as you can't write 1/3 in decimal with a finite number of digits, computers can't store exact values sometimes. Run the code below and you will have your answer.
radiusincrement = 1;
thetaincrement = 45;
thetatotal=3;
k=1;
for i=1:1:5/radiusincrement %two for loops that will sweep through wafer points
for j=1:1:thetatotal
r(i,j) = (i-1)*radiusincrement;
theta(i,j) = (j-1)*thetaincrement;
x(i,j) = r(i,j).*cos(theta(i,j).*pi/180);
y(i,j) = r(i,j).*sin(theta(i,j).*pi/180);
point = [x(i,j) y(i,j) 0];
if point(1)==point(2)
kx(k)=x(i,j);
ky(k)=y(i,j);
k=k+1;
elseif abs(point(1)-point(2))<=(1e-10)
disp('you should have compared against a tolerance')
end
end
end
Two side notes:
If x and y are equal, why bothering storing them separately?
Did you consider doing this with an array operation?
  2 件のコメント
Walker Boldman
Walker Boldman 2020 年 5 月 13 日
haha thanks!
Yes, I considered that. The next step in this is to make a matrix with x, y, and about 4 other arrays that makes plotting and interpreting results easy. This was just getting me stuck. Thanks for the edit!
Rik
Rik 2020 年 5 月 13 日
You're welcome. If I solved your question, please consider marking it as accepted answer, if not, feel free to comment with your remaining issues.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by