Factorial Function Setting problem
8 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(2 个)
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.
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 个评论
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 Center 和 File Exchange 中查找有关 Performance and Memory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!