필터 지우기
필터 지우기

How to compute factorial if input is vector or matrix?

조회 수: 2 (최근 30일)
NIANNIAN
NIANNIAN 2014년 11월 16일
답변: MA 2014년 11월 16일
I am solving a problem which asks to create a function to express factorial without using build-in functions such as factorial, prod or cumprod.
Actually, I have written down the function.Here is my code:
f=1;
for i=n:-1:1
f=f*i;
end
This function actually works. However I am wondering how to improve my function, if the input is a vector or even matrix rather than a scalar. But I am stuck now because i could not use any build-in functions. Could anybody help me or even just give me some hints for how to do so? Thank you so much.
  댓글 수: 1
Geoff Hayes
Geoff Hayes 2014년 11월 16일
The easiest (and probably not the most efficient) method to try computing the factorial of each element in the vector or matrix, is to iterate over each element and compute its factorial. Determine the number of rows and columns in your matrix (or vector) and just use a couple of for loops to iterate over each element.

댓글을 달려면 로그인하십시오.

답변 (1개)

MA
MA 2014년 11월 16일
format long g
A=[1 2 3 50;4 5 6 2;9 8 7 11];
for i=1:size(A,1)
for j=1:size(A,2)
A(i,j)=factorial(A(i,j));
end
end
A

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by