Function with varying number of for loops
7 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(1 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!