Results 1 to 4 of 4

Math Help - implement recursive factorial in mat lab

  1. #1
    Junior Member
    Joined
    May 2010
    Posts
    39

    implement recursive factorial in mat lab

    Code:
    function rec(n)
    
    if(n==0) return 1;
        
    else return n * rec(n-1);   
        
    end
    The above code doesn't work .


    Please help.
    Follow Math Help Forum on Facebook and Google+

  2. #2
    Grand Panjandrum
    Joined
    Nov 2005
    From
    someplace
    Posts
    14,972
    Thanks
    4
    Quote Originally Posted by ilikec View Post
    Code:
    function rec(n)
    
    if(n==0) return 1;
        
    else return n * rec(n-1);   
        
    end
    The above code doesn't work .


    Please help.
    That is not how you set up a return value in matlab, the following should work:

    Code:
    function rv=rec(n)
    
    if(n<=1) 
        rv=1;
    else 
        rv=n * rec(n-1);   
    end
    Follow Math Help Forum on Facebook and Google+

  3. #3
    Member
    Joined
    Mar 2007
    Posts
    206
    Awards
    1
    Your syntax is wrong. You cant use return to return a value from a matlab function, you can only use it to exit exit the function therefore you need to define your output value before using the return statement.
    Code:
    function a = rec(n)
    if(n==1)
        a = 1;
        return
    else
        a = n * rec(n-1); 
    end
    Elbarto
    Follow Math Help Forum on Facebook and Google+

  4. #4
    Member
    Joined
    Mar 2007
    Posts
    206
    Awards
    1
    Beat me by 2 minutes CB

    I should also clarify that as in CB's code the return statement isn't necessary in this case, but I included it in my code to show how it should be used since I think it is where you are getting matlab confused with other languages like C or python etc.
    Follow Math Help Forum on Facebook and Google+

Similar Math Help Forum Discussions

  1. Replies: 1
    Last Post: September 11th 2010, 08:40 PM
  2. Factorial N
    Posted in the Pre-Calculus Forum
    Replies: 1
    Last Post: August 28th 2010, 10:18 PM
  3. implement algorithms
    Posted in the Math Software Forum
    Replies: 0
    Last Post: May 1st 2009, 03:29 AM
  4. Primitive Recursive vs Recursive Functions
    Posted in the Discrete Math Forum
    Replies: 2
    Last Post: January 29th 2009, 07:32 AM
  5. factorial
    Posted in the Algebra Forum
    Replies: 3
    Last Post: January 15th 2009, 07:13 AM

Search Tags


/mathhelpforum @mathhelpforum