break command

조회 수: 5 (최근 30일)
etcann
etcann 2011년 11월 3일
Hello,
I have a question in break command.
a=zeros(30,1);
a(1)=1;
for i=1:29
a(i+1)=a(i)+1;
if a(i)>20
break
end
end
a
And I got a result of a'=[1 2 ... 22 0 0 0 ...0] Well, I wanted it looked like a'=[1 2 ... 20 0 0 0 ...0]
What's wrong with my code? Thanks a lot in advance.

답변 (2개)

Christopher Kanan
Christopher Kanan 2011년 11월 3일
I assume you want this:
a=zeros(30,1);
a(1)=1;
for i=1:29
a(i+1)=a(i)+1;
if a(i+1)>=20
break;
end;
end;
a
However, if you just want the first 20 elements to be 1:20, then you could just do, a = zeros(30, 1);a(1:20) = 1:20;

Fangjun Jiang
Fangjun Jiang 2011년 11월 3일
You can figure it out by going through the for-loop in your brain. The first time that a(i)>20 is satisfied is when a(i)==21, right? Because even if a(i)==20, it won't satisfy a(i)>20. By that time, you've already had a(i+1)=a(i)+1. No wonder that last non-zero value is 22. The code is doing exactly what you tell it to do.
  댓글 수: 1
Jan
Jan 2011년 11월 3일
@etcann: Instead of the brain, you can use the debugger also: Set a breakpoint in your code and step through the execution line by line. Then you will see, that "a(i)>20" triggers at i==21 and therefore "a(21+1)" has been set to 22 already.

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

카테고리

Help CenterFile Exchange에서 Develop Apps Using App Designer에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by