Failure of the Continue command in a for-loop

5 次查看(过去 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?

采纳的回答

Star Strider
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).

更多回答(1 个)

Image Analyst
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 个评论
Robert Mason
Robert Mason 2016-7-31
j = [1 5] does the same job in this case as j = 1:5 in my version of Matlab.
Unfortunately, I tried using j= 1:5 and it does not fix the original problem I described regarding the continue command.
Image Analyst
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 CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by