# Matlab Vector Factorial Function

• Jan 30th 2010, 07:13 AM
redherring
Matlab Vector Factorial Function
Hi there,

I'm in a thermal physics course this term where we have had a very...short...introduction to Matlab to say the least.

I have to write a simple code for positive integers (assumed) to calculate the factorial of an array, for example, so that I can plot it against the integer value.

My code so far is:

function z = n_fact(N);
z = N;
x = 0;
for count=2:N
x =(N-count+1);
z = x.*z;
end

It can only accept integers...how can I get it so that it iterates individual values of an arary into the function?

Any help would be very much appreciated. Thanks!
• Jan 30th 2010, 07:30 AM
CaptainBlack
Quote:

Originally Posted by redherring
Hi there,

I'm in a thermal physics course this term where we have had a very...short...introduction to Matlab to say the least.

I have to write a simple code for positive integers (assumed) to calculate the factorial of an array, for example, so that I can plot it against the integer value.

My code so far is:

function z = n_fact(N);
z = N;
x = 0;
for count=2:N
x =(N-count+1);
z = x.*z;
end

It can only accept integers...how can I get it so that it iterates individual values of an arary into the function?

Any help would be very much appreciated. Thanks!

First your function is horribly over complicated

For a scalar try:

Code:

```function  rv=CBfak(N)   rv=1;   for idx=2:N     rv=rv*idx;  %* and .* are equivalent here since both operands are scalar   end```
Now write a vector wrapper

Code:

```function rv=CBVecFak(N)   ll=length(N);   rv=ones(size(N));   for idx=1:ll     rv(idx)=CBfak(N(idx));   end```
You will have to test this code because I haven't

CB
• Jan 31st 2010, 06:39 AM
redherring
Thank you very much! That works nicely :)
Thanks again.

RH