While loop in while loop; Shortening

23 ビュー (過去 30 日間)
M_Szer
M_Szer 2019 年 10 月 7 日
コメント済み: Turlough Hughes 2019 年 10 月 7 日
I want an overall while loop that is executed until a certain condition is true (let's say J=13).
The whole loop starts with J=5 and j=1 and inside the while loop j is raised +1 until j =J. Then the second while loop starts with J = J+1.
How can I shorten this code with one while loop ?
J=5;
j=1;
while (j<7)
if (j>J)
break
end
z=63*pi*(J-j);
j=j+1;
disp(z)
end
J=J+1;
j=1;
while (j<7)
if (j>J)
break
end
z=63*pi*(J-j);
j=j+1;
disp(z)
end
J=J+1;
j=1;
while (j<7)
if (j>J)
break
end
z=63*pi*(J-j);
j=j+1;
disp(z)
end
..... (and so on until J=13)

採用された回答

Turlough Hughes
Turlough Hughes 2019 年 10 月 7 日
編集済み: Turlough Hughes 2019 年 10 月 7 日
You could try the following.
J=5;
while J<13
if J>=7
j=1:6;
else
j=1:J;
end
z=63*pi.*(J-j); %piecewise multiplication
disp(z)
J=J+1;
end
This satisfies the conditions of j less than or equal to J and j less than 7.
Note the .* operation (see link)
When j is not changing in size, i.e. after the first two iterations of the loop, you could in fact get a solution therein without any loops:
j=1:6;
J=[7:13]';
z=63*pi.*(J-j)
  2 件のコメント
M_Szer
M_Szer 2019 年 10 月 7 日
Thank you !!
Is it possible to create a table with J on the row , j on the column and z in the cross section ?
j\J 5 6 7 8 9 ...
1 z z z z z
2 z z z z z
3 z z z z z
.....
Turlough Hughes
Turlough Hughes 2019 年 10 月 7 日
You just need to rearrange your order when initially specifying j and J. i.e. j is now a column vector while J is now a row vector.
j=[1:6]';
J=7:13;
z=63*pi.*(J-j)

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

その他の回答 (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