How to make recursive for loop
    9 views (last 30 days)
  
       Show older comments
    
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.
0 Comments
Answers (1)
  Walter Roberson
      
      
 on 16 Nov 2017
        I recommend the "odometer" pattern when the number of for loops must be handled dynamically.
0 Comments
See Also
Categories
				Find more on Loops and Conditional Statements in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
