How to cycle through elements in an array in Matlab

33 ビュー (過去 30 日間)
Alif Aiman Ahmad Zukiman
Alif Aiman Ahmad Zukiman 2024 年 4 月 19 日
Hello there, I am trying to cycle through the elements in an array given a specified number of iterations. For other languages where the first element is 0, I can easily utilize the modulo command and so when the iteration is equal to the modulo it will evaluate to 0 and the array in question will start from the beginning again. However, with MATLAB, since the elements start with 1, I cannot utilize the same idea. How do I get around this? And very much possibly without the use of if else anywhere. Thank you!

採用された回答

the cyclist
the cyclist 2024 年 4 月 19 日
編集済み: the cyclist 2024 年 4 月 19 日
You can utilize the same idea. Just offset by one inside outside mod():
A = [2 3 5 7];
% Illustrate the mod() cycle with offset
for iteration = 1:8
idx = mod(iteration-1,length(A))+1
end
idx = 1
idx = 2
idx = 3
idx = 4
idx = 1
idx = 2
idx = 3
idx = 4
% Index into the array
for iteration = 1:8
idx = mod(iteration-1,length(A))+1;
A(idx)
end
ans = 2
ans = 3
ans = 5
ans = 7
ans = 2
ans = 3
ans = 5
ans = 7

その他の回答 (1 件)

Voss
Voss 2024 年 4 月 19 日

To account for indexing in MATLAB starting with 1, subtract 1 from the iteration number, perform mod(), then add 1 to the result.

idx = mod(iteration-1,N)+1;

That will give idx values starting with 1 when iteration is 1, and as iteration increases, idx increases to N and then repeats starting with 1 again when iteration is N+1, and so on.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by