Contents Previous Next Subchapters Current Chapters-> definingfun return clearfun arguments nargin argnumber varwithfun recursion forward funarguments multiplereturn nargout funvar localvar localfun localvarfun feval profile Parent Chapters-> Omatrix6 userdefined recursion Search Tools-> contents reference index search

Using Recursion
A recursive function references itself. The following function uses recursion to calculate the factorial of a number. ```      clear      function factorial(n) begin           if n==1 then return 1           return n * factorial(n - 1)      end ``` If you then enter the text above followed by ```      print factorial(3) ``` O-Matrix will respond ```      6 ``` The reference factorial(3) caused the following evaluations: ```      function factorial(3) begin           if 3==1 then return 1           return 3 * factorial(2) # factorial(2) returns 2*1      end      function factorial(2) begin           if 2==1 then return 1           return 2 * factorial(1) # factorial(1) returns 1      end      function factorial(1) begin           if 1==1 then return 1   # returns 1           return 1 * factorial(0)      end ```