The factorial of n is defined as n!=1×2×3×···×n. Write a Matlab.m function myfactorial to compute factorials in a recursive manner by calling the m-function myfactorial itself. Test your m-function myfactorial forn = 0,1,2,3,4,5,6,7,8,9,10.
MATLAB Script:
close all
clear
clc
for n = 0:1:10
fprintf('myfactorial(n = %2d) = %d\n', n, myfactorial(n))
end
function f = myfactorial(n)
if n == 0
f = 1;
return
end
f = n * myfactorial(n - 1);
end
Output:
myfactorial(n = 0) = 1
myfactorial(n = 1) = 1
myfactorial(n = 2) = 2
myfactorial(n = 3) = 6
myfactorial(n = 4) = 24
myfactorial(n = 5) = 120
myfactorial(n = 6) = 720
myfactorial(n = 7) = 5040
myfactorial(n = 8) = 40320
myfactorial(n = 9) = 362880
myfactorial(n = 10) = 3628800
Get Answers For Free
Most questions answered within 1 hours.