MATLAB: Failure of the Continue command in a for-loop

for loopMATLAB

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?

Best Answer

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