Failure of the Continue command in a for-loop
6 ビュー (過去 30 日間)
古いコメントを表示
I cannot get the continue command to work in for-loops. For instance, with the code:
q(1) = 1;
q(2) = 2;
q(3) = 3;
q(4) = 4;
q(5) = 5;
for j=1:5
if j==2
continue
end
qv=q
end
I expected the outcome of executing this code to be qv = [1 3 4 5], however the actual outcome is qv = [1 2 3 4 5].
Any suggestions as to how to get "continue" to work in this for-loop so that the output qv = [1 3 4 5] results?
0 件のコメント
採用された回答
Star Strider
2016 年 7 月 31 日
You’re not ‘building’ your ‘qv’ vector. You must also index ‘q’ since:
qv = q
sets ‘qv’ to all of ‘q’ in each iteration.
See if this does what you want:
q(1) = 1;
q(2) = 2;
q(3) = 3;
q(4) = 4;
q(5) = 5;
qv = []; % Initialise ‘qv’
for j=1:5
if j==2
continue
end
qv=[qv q(j)]; % Concatenate New Value
end
qv
qv =
1 3 4 5
One other observation:
q = 1:5;
q = [1 2 3 4 5];
will do the same assignment to ‘q’. The first creates a sequential vector, the second can contain any numbers you want (here consecutive, but they don’t have to be).
0 件のコメント
その他の回答 (1 件)
Image Analyst
2016 年 7 月 31 日
You constructed the for loop incorrectly. j takes on only the values 1 and 5. If you want it to take on the values 1,2,3,4 & 5, do this:
for j = 1 : 5
By the way, I fixed your code formatting. For your next post, read this link to learn how to format.
Also see this link to learn how you can step through code to see what values, such as your "j", take on at each line in your program.
2 件のコメント
Image Analyst
2016 年 7 月 31 日
I seriously doubt that.
for j = [1 5]
disp(j);
end
for j = 1 : 5
disp(j);
end
shows
1
5
1
2
3
4
5
as expected. And I'm virtually 100% certain your version would too. What version do you have? I'd have to see a screenshot of you running the above code and getting something different to believe otherwise.
Anyway, Star corrected your two errors, one in constructing j and one in constructing qv.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!