Counter in for loop is not working as expected

1 回表示 (過去 30 日間)
Rashed Fairouz
Rashed Fairouz 2020 年 6 月 26 日
コメント済み: Walter Roberson 2020 年 6 月 27 日
I want the matrix to display [1 1 1 2 2 2 2 2 1 1 1 2 2 2 2 2.........5 times].
Nel=100
Neln=20
Nelnl1=5
Nelnl2=15
Code:
Mats=zeros(1,Nel);
for i=1:Nel
j=1;
if j<=Nelnl1
Mats(1,i)=1;
i=i+1;
j=j+1;
elseif j>Nelnl1&&j<=Nelnl2
Mats(1,i)=2;
i=i+1;
j=j+1;
end
end
Mats
Doesn't give me correct value. It just displays all 1's at the end.
  2 件のコメント
KSSV
KSSV 2020 年 6 月 27 日
You are alwasy filling 1 and 2 in the matrix...
Mats(1,i)=1;
Mats(1,i)=2;
Walter Roberson
Walter Roberson 2020 年 6 月 27 日
Until you know matlab much better, and have very good reasons for doing so, you should adopt the rule that you never modify a for loop variable inside its for loop. Elsewhere I have described in detail how for loops work in MATLAB, but at this point you should just treat it as being an error to modify i within for i. (It is not actually an error, but it does not do what you expect and is very likely to be a source of bugs)

サインインしてコメントする。

回答 (1 件)

KALYAN ACHARJYA
KALYAN ACHARJYA 2020 年 6 月 27 日
data1=ones(1,3);
data2=1+ones(1,5);
result=repmat([data1,data2],1,5)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by