Function with varying number of for loops
7 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Jan
on 20 Jun 2017
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 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!