Search code examples
matlabrecursionfactorial

how can i write nested recursive function in matlab


    I want to write nested recursive function. 
    Example: Calculate sum of factorial of 1 to n numbers.

myfact(n) function calculate factorial of n.

function [ fact ] = myfact( x )
temp = 0;
if (x == 1)
    temp = 1;
else
    temp = x*myfact(x-1);
end
fact = temp;
end 

myfactSum() function calculate the sum of return values of "myfact". factNums is an array which contains each value's factorial. For example : factNums(2)=2!

function [total] = myfactSum(n,factNums)
    if(n==1)
       return
    else
    result = myfact(n);
    factNums(n) = result;
    total=sum(factNums);
    myfactSum(n-1,factNums);
    end
end

Testing it script above ;

n = 4;
factNums = zeros(1,n);
x=myfactnum(n,factNums);

y=0;
for i=1:checkValues
   y=y+myfact(i); 
end

At the results of script x=24, y=33 One recursive and loop find right answer, however nested recursive functions return only the factorial of last value. I try to debug the recursive functions, it fill the factNums with values [1,2,6,24] end of the function values, but when it back to main script values dissapeared.

variable values after i run the script


Solution

  • I change myfactSum, and it works :) It is so simple :)

    function [sum] = myfactnum(n)
    
    temp=1;    
        if(n==0)
           temp=0;
        else
        temp=myfact(n)+myfactnum(n-1);
        end
    sum=temp;    
    end