How do I create multiple for loops depending on the array size?

17 ビュー (過去 30 日間)
Matthias Wieland
Matthias Wieland 2018 年 5 月 20 日
編集済み: the cyclist 2018 年 5 月 23 日
I would like to iterate over multiple for-loops, but the amount of for-loops depends on the size of a vector. Is there a good way to do this, without using a lot of if-statements?
arr = [a1 a2 ... an]
for a1=1:...
for a2=1:...
...
for an=1:...
%do something
end
end
end
for for examle if the vector arr has "n" entries I would like to have "n" for loops.

採用された回答

Jan
Jan 2018 年 5 月 20 日
編集済み: Jan 2018 年 5 月 20 日
As in the answers you find in Stephen's links: Use an index vector instead of a list of for loops. Replace:
arr = [a1 a2 ... an]
for i1 = 1:a1
for i2 = 1:a2
...
for in = 1:an
%do something with [i1, i2, ... in]
end
end
end
By:
% Loops from 1 to a(n):
n = length(arr)
ini = ones(1, n);
fin = [a1 a2 ... an];
v = ini;
iterN = prod(find - ini + 1); % Number of iterations
for iter = 1:iterN
% Do something with v
...
% Increase index vector:
for k = 1:n % Or n:-1:1, as you want to
if v(k) < fin(k)
v(k) = v(k) + 1;
break; % Stop "for k" loop
end
v(k) = ini(k); % Reset this index
end
end

その他の回答 (2 件)

Stephen23
Stephen23 2018 年 5 月 20 日
編集済み: Stephen23 2018 年 5 月 20 日
A recursive function is the obvious solution, although this depends on whether you count recursive functions as being "a good way to do this", as they are famously fickle beasts, and are not always easy to debug. Often the best solution is to use indexing, as Jan Simon explained in this answer. Recursive functions, indexing and other solutions have been discussed before:

Walter Roberson
Walter Roberson 2018 年 5 月 20 日
編集済み: the cyclist 2018 年 5 月 23 日

カテゴリ

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