Function with varying number of for loops

7 ビュー (過去 30 日間)
Mitchell Morin
Mitchell Morin 2017 年 6 月 20 日
回答済み: Jan 2017 年 6 月 20 日
My input is a number (most likely between 1 and 5) and I need a code to create n number of for loops with my output in the last for loop. Each dimension would have length 14, so in total there would be 14^n values
Something like this
n=1
for a=1:14
Output(a)=1 or 0
end
n=2
for a=1:14
for b=1:14
Output(a,b)=1 or 0
end
end
It has to create each for loop and not just an empty array of dimensions n
Any help would be appreciated, thank you in advance!

回答 (1 件)

Jan
Jan 2017 年 6 月 20 日
Do not use a bunch of nested for loops, but an index vector and one loop:
n = 5; % Number of loops
v = ones(1, n); % Index vector
Output = zeros(repmat(14, n));
ready = false;
while ~ready
index = sub2ind(size(Output), v);
Output(index) = 1 or 0 ???
% Update the index vector:
ready = true; % Assume that the WHILE loop is ready
for k = 1:n
v(k) = v(k) + 1;
if v(k) <= 14
ready = false;
break; % v(k) increased successfully, leave "for k" loop
end
v(k) = 1; % v(k) reached the limit, reset it
end
end

カテゴリ

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