Recursive loops in MATLAB
이전 댓글 표시
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
David Goodmanson
2017년 3월 3일
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
2017년 3월 3일
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 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!