break command

5 Ansichten (letzte 30 Tage)
etcann
etcann am 3 Nov. 2011
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.

Antworten (2)

Christopher Kanan
Christopher Kanan am 3 Nov. 2011
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 am 3 Nov. 2011
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 Kommentar
Jan
Jan am 3 Nov. 2011
@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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Develop Apps Using App Designer finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by