In this lecture, we talked about RECURSION. We wrote two recursive functions: one to calculate the factorial of a given number (factorial.m) , the other one to calculate the sum of the elements of a given vector of numbers (mysum.m). See below to see how we wrote the functions and then how we called the fnctions. Prof. Aydin >> !vim factorial.m "factorial.m" 14L, 184C written >> >> type factorial.m function result = factorial(n) % inputs: % n = the number % outputs: % result = the factorial of the number n % % Base case: if the number is less than equal to 1 if (n <=1) result = 1; % the recursive case: if the number is greater than 1 else result = n * factorial(n-1); end >> clc >> factorial(1) ans = 1 >> factorial(2) ans = 2 >> factorial(3) ans = 6 >> factorial(4) ans = 24 >> factorial(5) ans = 120 >> factorial(0) ans = 1 >> factorial(-1) ans = 1 >> clc >> !vim mysum.m "mysum.m" [New] 14L, 191C written >> type mysum.m function result = mysum(v) % inputs: % v: a vector of numbers % outputs: % sum: the sum of the numbers of vector v % notes: % [1] the if statement for base case 1 (below), can also be written as: if % (isempty(v) == true) % [2] note that there are two base cases in this recursive definition of the % sum (see below) % base case #1: if the vector is empty if (length(v) == 0) result = 0; % base case #2: if the vector has one element in it else if (length(v) == 1) result = v(1); % the recursive case: self-calling the function, on a smaller part of the % vector (i.e., from second element to the last element) else result = v(1) + mysum(v(2:length(v))); end % if end %function >> mysum([]) ans = 0 >> mysum([133]) ans = 133 >> mysum([133 5]) ans = 138 >> mysum([133 5 -5]) ans = 133 >> V = [120 3 -2 1] V = 120 3 -2 1 >> mysum(V) ans = 122 >>