Variables number of for loops using recursion
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hello,
I have been thinking to do this for a while, and have been searching here and there and no results.
Lets say the input=recursion(d,f) , where each of d and f is a vector of n.
I want the function code to do exactly as:
for i=1:f(1)
for i2=1:f(2)
for i3=1:f(3)
.......
.......
for in=1:f(n)
_do something such as calling other function to run other software program in background_
d=d+[0,0,...,1]
end
.......
.......
d=d+[0,0,1....]
end
d=d+[0,1,0....]
end
d=d+[1,0,0,....]
end
I think the only way to do this is through recursion, and somehow I prefer that way, because I need to learn it also how to do recursion properly.
Please advise how to do this.
0 comentarios
Respuestas (1)
James Tursa
el 29 de Sept. de 2016
Does this do what you want (assumes all of the f values are positive integers):
function forloops(d,f)
n = ones(1,numel(f)+1); % Index vector (first one is a dummy for programming purposes)
F = [2 f(:)']; % Index limit vector (first one is a dummy for programming purposes)
D = [0 d(:)']; % d vector (first one is a dummy for programming purposes)
while( true )
% Do your stuff here
% Equivalent for-loop indexes are in n(2:end)
% Equivalent d vector is in D(2:end)
n(end) = n(end) + 1; % Increment "inner" index
D(end) = D(end) + 1; % Increment "inner" d vector spot
k = n > F;
while( any( k ) ) % Loop to cycle any indexes that are over limit
x = find(k,1); % Find the one that just went over the limit
n(x) = 1; % Set the one that is over the limit back to 1 ...
n(x-1) = n(x-1) + 1; % ... and increment the immediate "outer" loop index
D(x-1) = D(x-1) + 1; % Also increment the related "outer" d vector spot
k = n > F; % Check to see if the "outer" one went over the limit
end
if( n(1) == 2 ) % If 1st dummy index is 2, we are done
break;
end
end
end
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!