break command

4 views (last 30 days)
etcann
etcann on 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.

Answers (2)

Christopher Kanan
Christopher Kanan on 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 on 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 Comment
Jan
Jan on 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.

Sign in to comment.

Categories

Find more on Develop Apps Using App Designer in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!