MATLAB - 阶乘



非负整数 'n' 的阶乘,记为 'n!',定义为从 1 到 'n' 的所有正整数的乘积。因此,在数学上,语法为:

n! = 1 × 2 × 3 × ... × n

例如,5 的阶乘将是

5! = 1 × 2 × 3 × 4 × 5  =  120

语法

result = factorial(n)
  • 这里 n 是您想要计算阶乘的非负整数。
  • Result 将存储计算出的阶乘值。

在数学符号中,n 阶乘,记为 n!,通常用感叹号表示。需要注意的是,在 MATLAB 中,使用 n! 作为计算 n 阶乘的语法是无效的。

计算阶乘的示例

让我们看几个计算给定数字的阶乘的示例。

示例 1:计算数字 n 的阶乘

要计算 5!,您可以在 MATLAB 中使用 factorial() 函数:

result = factorial(5)

当您在 matlab 命令窗口中执行时,输出为:

>> result = factorial(5)

result = 120

以上代码将给出结果:result = 120,因为 5! 等于 120。

示例 2:大数的阶乘

MATLAB 甚至可以处理大数的阶乘。

n = 20;
result = factorial(n)

当您在 matlab 命令窗口中执行相同操作时,输出为:

>> n = 20;
result = factorial(n)

result =  2.4329e+18

示例 3:计算数组的阶乘

假设您有一个数组 A,其中包含几个要计算阶乘的值:

A = [3, 4, 5, 6, 7];
result = factorial(A)

输出为:

result = 

    6  24  120  720  5040

示例 4:计算数组的阶乘

考虑下面显示的数组,我们将为其计算阶乘。

num_array = [0 1 2; 3 4 5];
result = factorial(num_array)

执行后,输出为:

result =

   1     1     2
   6    24   120

示例 5:无符号整数的阶乘

uints = uint64([7 10 15 20]);
result = factorial(uints)

所以我们有无符号整数向量 [7 10 15 20]

执行后,输出为:

result = 

   5.0400e+03   3.6288e+06   1.3077e+12   2.4329e+18

在 Matlab 中使用函数计算阶乘

您可以创建一个 MATLAB 函数来计算数字的阶乘。以下是一个简单的函数来执行此操作:

function fact = factorial_custom(n)
   if n < 0
      error('Factorial is undefined for negative numbers.');
   elseif n == 0 || n == 1
      fact = 1;
   else
      fact = 1;
      for i = 2:n
         fact = fact * i;
      end
   end
end

此 factorial_custom 函数接受输入 n,并使用 for 循环计算 n 的阶乘。它处理负数并为它们返回错误消息。对于 0 和 1,阶乘定义为 1。对于其他正整数,它使用循环计算阶乘。

您可以在 matlab 中按如下方式执行:

factorial custom

使用 For 循环计算阶乘

您可以使用 for 循环计算阶乘,如下所示:

n=6;
result = 1;
for i = 1:n
   result = result * i;
end

这里,result 初始化为 1,循环将其乘以从 1 到 n 的数字。

当您在 matlab 命令窗口中执行相同操作时:

>> n = 6;
result = 1;
for i = 1:n
   result = result * i;
end
>> result

result =

   720

使用 While 循环计算阶乘

阶乘也可以用 while 循环计算:

n = 6;
result = 1;
i = 1;
while i <= n
   result = result * i;
   i = i + 1;
end

此代码类似于 for 循环方法,但使用 while 循环代替。

在 matlab 命令窗口中的执行如下所示:

>> n = 6;
   result = 1;
   i = 1;
   while i <= n
      result = result * i;
      i = i + 1;
   end
>> result

result =

   720
广告

© . All rights reserved.