How to make recursive for loop

17 次查看(过去 30 天)
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