break command

6 ビュー (過去 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 Center および File ExchangeDevelop 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