What is the best practice in MATLAB to increase a variable in a cycling way?

1 回表示 (過去 30 日間)
jackxujh
jackxujh 2017 年 11 月 26 日
コメント済み: jackxujh 2017 年 11 月 26 日
I have some variables that need to be incremented in a loop, and should go back to 0 when hit some value. The current way I am doing this is:
cluster = 1;
for I = 1 : n
cluster = clusterNumber + 1;
if cluster == max
cluster = 1;
end
end
However, as the script goes on, there are a lot of these cases.
So, is there a function in MATLAB or a better way to do this? For example, writing a function like this:
cycling-increase(count, interval, max, backToValue);
Thanks!
Meanwhile, this is my first question. Please do tell me if anything I put up does not meet the rules or conventions of MATLAB Answers. Thanks again!

採用された回答

Stephen23
Stephen23 2017 年 11 月 26 日
編集済み: Stephen23 2017 年 11 月 26 日
Just use mod:
for k = 1:10
1+mod(k-1,5)
end
which displays:
ans = 1
ans = 2
ans = 3
ans = 4
ans = 5
ans = 1
ans = 2
ans = 3
ans = 4
ans = 5
  1 件のコメント
jackxujh
jackxujh 2017 年 11 月 26 日
That is such a genius and elegant solution! Thanks! Really appreciate it!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeParticle & Nuclear Physics についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!