MATLAB-A factorial is the product of all positive integers less than or equal to
ID: 3805292 • Letter: M
Question
MATLAB-A factorial is the product of all positive integers less than or equal to a given positive number. Write a function that will receive as input either a single positive number or a vector of positive numbers and return the factorials as a vector. For example, if 5! is passed to the function, the returned value would be 120 (1*2*3*4*5). Likewise, if a vector [6 4 2 1] is passed, the function will return a vector with the factorial of every element in the input vector. Make sure you use a for loop in your solution.
Explanation / Answer
function f = fact(n)
f = 1
if (n == 0 || n == 1)
f = 1;
return;
else
for i = 1 : n
f = f*i
end
end
end
function a = fctorial(n)
if (isscalar(n) == 1)
a = fact(n);
return;
else
a = zeros(length(n),1)
for i = 1:length(n)
a(i) = fact(n(i))
end
end
end
a = fctorial(4);
a = fctorial([6 4 2 1]);
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.