Borrar filtros
Borrar filtros

How to make recursive for loop

6 visualizaciones (últimos 30 días)
sreelatha Aihloor Subramanyam
sreelatha Aihloor Subramanyam el 16 de Nov. de 2017
Respondida: Walter Roberson el 16 de Nov. de 2017
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.

Respuestas (1)

Walter Roberson
Walter Roberson el 16 de Nov. de 2017

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by