Failure of the Continue command in a for-loop
5 views (last 30 days)
Show older comments
Robert Mason
on 31 Jul 2016
Commented: Image Analyst
on 31 Jul 2016
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 Comments
Accepted Answer
Star Strider
on 31 Jul 2016
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 Comments
More Answers (1)
Image Analyst
on 31 Jul 2016
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 Comments
Image Analyst
on 31 Jul 2016
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.
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!