Variables number of for loops using recursion
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
James Tursa
am 29 Sep. 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 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!