How to write a matlab-function which counts the n! with help of a vector?
Show older comments
If we call n=4, the answer should be a vector equaled to [1! 2! 3! 4!]. If we do like this
function [f]=nfac(n)
h=1
for i=1:n
h=h*i
end;
end
we will get a number when we call the function , but how should u do if u want a vector?
Accepted Answer
More Answers (1)
the cyclist
on 7 Feb 2017
Edited: the cyclist
on 7 Feb 2017
The most straightforward extension of the code you have written is probably this ...
function [f]=nfac(n)
h = zeros(1,n);
h(1)=1;
for i=2:n
h(i)=h(i-1)*i
end;
end
There are more efficient ways. Hints:
- This can be vectorized
- MATLAB has a function for calculating the factorial function
Categories
Find more on MATLAB Coder in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!