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.