Explain how many times a for loop will execute

I can add ires to see the result, I am not sure how to see how many times the loops will execute. If someone could explain how to do this that would be helpful. I have done several searches and tried using the break function, but if its really big number says -32687:32688, how does one tell how many times it loops. without counting each 64560 times. I have figured it out on smaller loops by putting the ii at the bottom of the code. This has a loop within a loop and I am lost.
ires = 0;
for index1 = 10: -2: 1
for index2 = 2:2:index1
if index2 == 6
break;
end
ires = ires + index2;
end
end

답변 (1개)

Mario Malic
Mario Malic 2020년 10월 10일
ires = 0;
for index1 = 10: -2: 1
for index2 = 2:2:index1
if index2 == 6
break;
end
ires = ires + 1; % index2 for what?
end
end
MATLAB enters first loop with index1 = 10, then proceeds in the second loop with index2 = 2. Within second loop it checks the if condition and adds 1 to ires. When the 'if' condition is fulfilled, it exits the second loop, and returns in the first one with index1 = 8 and so on.

댓글 수: 8

i understand how it works, I just don't know how to see how many times it loops
ires contains the number of loops done.
disp(ires)
doesn't that just display what ires is and not the actual number of times it loops? I just don't understand how your supposed to understand how many times the loop is performed?
ok if i add n_times=0; and then frprintf( 'number of times the loop %d\n',n_times);
I can see how many loops, but that is only for one loop not both loops. I hope this explains what i am asking.
ires = 0;n_times=0;
for index1 = 10: -2: 1
for index2 = 2:2:index1
if index2 == 6
break;
end
ires = ires + index2;
n_times=n_times + 1;
end
end
fprintf('ires is %d\n',ires);
fprintf('number of times the loop %d\n',n_times);
I misinterpred iris, thought that was the loop counter.
so any other ideas?
Mario Malic
Mario Malic 2020년 10월 10일
편집: Mario Malic 2020년 10월 10일
Your code is working, n_times counts both loops.
Okay, I just thought it was counting loop one. Well i gave it a solid try. Thanks for your help.

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

릴리스

R2019a

태그

질문:

2020년 10월 10일

댓글:

2020년 10월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by