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!