How to make recursive for loop

조회 수: 10 (최근 30일)
sreelatha Aihloor Subramanyam
sreelatha Aihloor Subramanyam 2017년 11월 16일
답변: Walter Roberson 2017년 11월 16일
I am trying to make recursive for loop for given for loop
sample program to achieve:
k=0;
k_prev1=0;
k_prev=0;
for t= 1:2
for i=1:2
for j=1:3
k=k+1;
end
k_new= k_prev+k;
k_prev=k_new;
k=k_new;
end
k_new= k_prev1+k;
k_prev1=k_new;
k=k_new;
end
My code is like this with two functions
function1
function x = fun(y,cmax)
k=length(cmax);
x_prev=0;
x_new=0;
for i= 1:cmax(k)
if y == 1
x = fun1(y,cmax,x_new);
x_new = x_prev+x;
x_prev= x_new;
x=x_new;
elseif y >=2
x= fun(y-1,cmax);
end
end
end
and another function is
function u = fun1(x,cmax,x_new)
if x==1
u=0;
for i = 1:cmax(x)
if x_new > 0
x_new= x_new+1;
else
u= u+1;
end
end
if(x_new >0)
u=x_new;
end
x_new=0;
end
and the function call is like
cmax=[3,2,2];
fun(3,cmax)
And I could not get result. but it was working fine for 2 for loops. But not for more than two.
my aim is to be able to generate 5 to 7 for for loops . And thought recursive looping would help.
Any help is highly appreciated.

답변 (1개)

Walter Roberson
Walter Roberson 2017년 11월 16일

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by