Factorial Function Setting problem

조회 수: 10 (최근 30일)
Kev W
Kev W 2016년 8월 10일
댓글: Star Strider 2016년 8월 10일
Hi, I just set up my code for a factorial function, shown below:
function y = my_factorial(x);
if x == 0
y = 1
else y = x * factorial(x-1);
end;
but Matlab keeps saying not enough input arguments. What's the problem of it?

답변 (2개)

Stephen23
Stephen23 2016년 8월 10일
편집: Stephen23 2016년 8월 10일
There is nothing wrong with your function, it works fine:
>> my_factorial(3)
ans = 6
The problem is how you are calling it. Are you clicking the Run button on the toolbar ? MATLAB made a poor design decision by adding that button, because now lots of beginners click that button and are surprised when their code does not work... in fact they are just forgetting to call their function with its required input arguments. Chances are you forgot to supply the input argument.
  댓글 수: 2
Kev W
Kev W 2016년 8월 10일
Cool stuff.Now the case is I would like to build a function for n!. What am I going to code to make it done?
Stephen23
Stephen23 2016년 8월 10일
편집: Stephen23 2016년 8월 10일
function y = myfun(x)
y = prod(1:x);
end

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


Star Strider
Star Strider 2016년 8월 10일
편집: Star Strider 2016년 8월 10일
You have to call your function with an argument in your script or in the Command Window. You cannot click ‘Run’ in the Editor.
EDIT — The easiest way to create your own factorial function:
my_factorial = @(n) prod(1:n);
  댓글 수: 2
Kev W
Kev W 2016년 8월 10일
편집: Star Strider 2016년 8월 10일
The hint asked us to write a code like this:
function y = your_func_name(x);
y = x;
end;
how do we use a form like thi sto write a n! function? (Purely new hand :( )
Star Strider
Star Strider 2016년 8월 10일
I would do it this way:
function y = my_factorial(x);
if rem(x,1) ~= 0
error('Argument ‘x’ must be an integer.')
end
y = prod(1:x);
end

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

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by