How to write a matlab-function which counts the n! with help of a vector?

6 views (last 30 days)
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

Roger Stafford
Roger Stafford on 7 Feb 2017
function f = nfac(n)
f = [];
h = 1;
for k = 1:n
h = h*k;
f = [f,h];
end
return

More Answers (1)

the cyclist
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!