Recursive loops in MATLAB
Show older comments
I have a question regarding recursive loops in MATLAB.
Suppose I have a variable called "dimension" with value 3. The script that I need to run has the following structure:
dimension=3;
order=5;
for i1=1:order
for i2=1:order
for i3=1:order
if i1+i2+i3<=order
disp([i1,i2,i3])
end
end
end
end
That is, if "dimension=3", 3 nested loops will be required to run this script.
If "dimension=4", then the script shown above becomes:
dimension=4;
order=5;
for i1=1:order
for i2=1:order
for i3=1:order
for i4=1:order
if i1+i2+i3+i4<=order
disp([i1,i2,i3,i4])
end
end
end
end
end
That is, 4 nested loops in this case. And so on.
To solve this problem, I tried the following first (without the if condition i1+i2...<=order shown above, because I didn't know how to incorporate it into the script):
function result=recursiveLoop(dimension,order,level,iter,counter,expression)
if nargin==2 % initial call
level=1;
iter=zeros(dimension,1);
counter=0;
expression=zeros(order^dimension,dimension);
end
for i=1:order
iter(level)=i;
counter=counter+1;
expression(counter,:)=iter;
if level==dimension && i==order
result=expression;
end
if level~=dimension
result=recursiveLoop(dimension,order,level+1,iter,counter,expression);
end
end
end
But the output is not the one that one would expect from the above definition. Any ideas about how to solve this problem using, say, a recursive function? Is there a better way to solve this problem?
Thank you,
Ricardo
2 Comments
David Goodmanson
on 3 Mar 2017
Hi Ricardo, do you care what order the results are displayed in, i.e. right now the last index changes most quickly and the first index changes least quickly.
Ricardo Prada
on 3 Mar 2017
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!