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