can any one tell how this break function works in this loop??

조회 수: 1 (최근 30일)
Abhishek sadasivan
Abhishek sadasivan 2014년 9월 15일
댓글: Abhishek sadasivan 2014년 9월 16일
can any one tell me how the break functions if there are two if conditions in a for loop ...
if true
% code
end
locs_Qwave=[ 100 150 90 1175 1 50]';
locs_Rwave=[116 170]';
q=0
k=1
for j=k:size(locs_Rwave)
for i=1:numel(locs_Qwave)
if (i== numel(locs_Qwave))
q=[q locs_Qwave(i)];
break;
end
if( locs_Qwave(i)>locs_Rwave(j))
q=[q locs_Qwave(i-1)];
break;
end
end
end

채택된 답변

Adam
Adam 2014년 9월 15일
편집: Adam 2014년 9월 15일
The second if statement is hit at j = 1, i = 2 so locs_Qwave(1) gets appended to q and it breaks out of the loop before the first if statement kicks in at all. Then we get j = 2 and now the second if statement kicks in at i = 4, adding locs_Qwave(3) to q. Again the first condition plays no part because it is not matched before the second condition matches and breaks out of the loop.
The first of condition appears to only be checking what would be the end of the for loop anyway so it will never activate before the final iteration. All it would do on its own is add a value to q after the for loop has ended which you could do without even having a for loop.
So with the other if statement in there too the first clause will only activate if the second clause is never matched.
  댓글 수: 3
Adam
Adam 2014년 9월 16일
You never reach the final iteration. j only runs from 1 to 2 so there are only two outer loops, the first breaks at i = 2, the second at i = 4 and that is the end of the for loop. i = 6 is never reached.
You can just add
q=[q locs_Qwave(end)];
after your for loop if you want that to always happen though. Or add locs_Qwave(end) twice if you want it to happen for each j.
Abhishek sadasivan
Abhishek sadasivan 2014년 9월 16일
Thank you very much ..I got it ..Thanks

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2014년 9월 15일
It looks like it should function. What's the problem? If either of those two conditions is met, it breaks out of the "i" for loop and continues on with the "j" for loop.
  댓글 수: 1
Abhishek sadasivan
Abhishek sadasivan 2014년 9월 15일
shall you explain how the break function in this problem.when I run this I got q = 0,100 and 90.If it breaks out from first loop during loop execution I think that it has to come as 0 ,50 ..I am not understanding how it became 0,100,90

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Install Products에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by