matlab写一个阶乘的文件
时间: 2023-06-18 21:06:17 浏览: 49
下面是一个简单的 MATLAB 阶乘函数的代码:
```matlab
function out = factorial(n)
% FACTORIAL Compute the factorial of a non-negative integer.
if n < 0 || floor(n) ~= n
error('Input must be a non-negative integer')
elseif n == 0
out = 1;
else
out = n * factorial(n-1);
end
end
```
在 MATLAB 中,将代码保存到一个名为 `factorial.m` 的文件中。然后,您可以在 MATLAB 命令窗口中调用该函数,例如:
```matlab
>> factorial(5)
ans =
120
```
该函数使用递归定义阶乘,注意在输入为负数或者小数时会报错。
相关问题
matlab编写一个m文件求n的阶乘
好的,以下是一个简单的 Matlab m 文件,可以求 n 的阶乘:
```
function result = factorial(n)
% 计算 n 的阶乘
if n == 0
result = 1;
else
result = n * factorial(n-1);
end
end
```
你可以在 Matlab 中打开一个新的 m 文件,复制粘贴上述代码,并保存后,在命令窗口中输入“factorial(n)”,其中 n 是你要求阶乘的数字,就可以得到结果了。
请帮我写一个matlab用for循环求n阶乘的函数文件
好的,下面是求n阶乘的Matlab函数文件(使用for循环):
```matlab
function result = fac(n)
% 输入n,返回n的阶乘
result = 1;
for i = 1:n
result = result * i;
end
end
```
使用方法:
1. 将上述代码保存为.m文件,例如fac.m。
2. 在Matlab命令窗口中输入`fac(n)`,其中n为需要求阶乘的数,回车即可得到结果。
注意:
1. 这个函数只能求正整数的阶乘。
2. 当n比较大时,阶乘结果可能会超出Matlab的数值范围,需要使用高精度计算方法。