跳轉到內容

MATLAB 程式設計/複數

來自華夏公益教科書,自由的教學讀物


複數 也在 MATLAB 中使用。
它由兩部分組成,一部分是實數,另一部分是虛數。它具有 的形式。
i 或 j 返回基本虛數單位。i 或 j 等於 -1 的平方根,公式為 ( )。
注意:符號 i 和 j 可以互換,因為 MATLAB 只將 j 轉換為 i,如果方程使用兩種不同的表示法,如下所示。

在 MATLAB 中聲明覆數

[編輯 | 編輯原始碼]

MATLAB 中的複數是具有實部和虛部的雙精度數。虛部使用字元“i”或“j”宣告。例如,要將變數宣告為“1 + i”,只需鍵入以下內容:

 >> compnum = 1 + i
 compnum = 1.000 + 1.000i

>>%Note:If you use j MATLAB still displays i on the screen
 >> compnum = 1 + j
 compnum = 1.000 + 1.000i

注意 1:即使使用 j 來表示複數,MATLAB 仍然會在螢幕上顯示 i

注意 2:由於 i 用作複數指示符,因此不建議將其用作變數,因為它會假設 i 是一個變數。

 >> i = 1; %bad practise to use i as variable
 >> a = 1 + i
 a = 2

但是,由於 MATLAB 通常不允許隱式乘法,因此仍然可以使用以下方式聲明覆數:

 >> i = 3;
 >> a = 1i + 1
 a = 1.000 + 1.000i

最好不要將 i 宣告為變數,但是,如果已經有一個使用 i 作為變數的複雜程式,並且需要使用複數,這可能是解決它的最佳方法。

如果要對複數進行算術運算,請確保將整個數字放在括號中,否則可能不會得到預期的結果。

複數 函式

[編輯 | 編輯原始碼]

但是,聲明覆數的最佳實踐是使用函式 complex

>>%Best practise to declare complex number in MATLAB
>> complex(2,6)

ans =
   2.0000 + 6.0000i

如果要宣告 虛數,只需使用負數的平方根,如下所示。

>> sqrt(-49)

ans =
   0.0000 + 7.0000i

要宣告多個複數,請建立兩個具有實數的行向量,以及另一個具有虛數的行向量。使用 complex 函式將它們組合起來

>> %create a vector consiots of real number
>> RE = [1,2,3]

RE =
     1     2     3

>> %create a vector consiots of imaginary number
>> IM = [4,5,6]

IM =
     4     5     6
>> %create 3 complex number 
>> complex(RE,IM)

ans =
   1.0000 + 4.0000i   2.0000 + 5.0000i   3.0000 + 6.0000i

建立複數的算術運算

[編輯 | 編輯原始碼]

MATLAB 中有幾種運算可以建立複數。其中之一是根據定義對負數求偶數根。

>> (-1)^0.5
ans = 0.000 + 1.000i
>> (-3)^0.25
ans = 0.9306 + 0.9306i

作為尤拉公式的結果,對負數求對數也會產生虛數答案。

>> log(-1)
ans = 0 + 3.1416i

此外,使用“roots”函式(針對多項式)或其他一些求根函式找到的函式的根通常會返回複數答案。

操作複數

[編輯 | 編輯原始碼]

查詢實數和虛數

[編輯 | 編輯原始碼]

首先,在程式設計時,區分給定矩陣是實數還是複數很有幫助,因為某些運算只能對實數執行。

由於複數沒有自己的類,因此 MATLAB 附帶了另一個名為“isreal”的函式來確定給定 矩陣 是否為實數。如果任何輸入為複數,它將返回 0。

>> A=[complex(2,3),complex(4,0)]

A =
   2.0000 + 3.0000i   4.0000 + 0.0000i

>> %returns 1 if complex number does not have an imaginary part and 0 if otherwise.
>> %A denotes the whole vectors
>> isreal(A)

ans =
  logical
   0
>> %A(2) denotes second complex number in the vector (4+0i)
>> isreal(A(2))

ans =
  logical
   1

請注意,由於兩者都是 double 類,因此 可以 在同一個陣列中包含實數和複數。
該函式的設定方式使您可以將其用作條件的一部分,以便只有當陣列 A 的所有元素都是實數時才執行一個塊。

要僅提取複數變數的實部,請使用 real 函式。要僅提取虛部,請使用 imag 函式。

>>%Extract real number from the complex number vector A
>> real(A)

ans =
     2     4

>>%Extract imaginary number from the complex number vector A
>> imag(A)

ans =
     3     0

複共軛

[編輯 | 編輯原始碼]
複共軛圖片

要找到複共軛,可以使用conj函式。如果複數Z是,那麼共軛Ẑ是

>> conj(A)

ans =
   2.0000 - 3.0000i   4.0000 + 0.0000i

相位角

[編輯 | 編輯原始碼]

要找到相位角,可以使用複數每個元素的弧度表示的相位角。

>> angle(A)

ans =
    0.9828         0

參考資料

[編輯 | 編輯原始碼]

[1]

  1. https://web.archive.org/web/20211006102547/https://www.maths.unsw.edu.au/sites/default/files/MatlabSelfPaced/lesson1/MatlabLesson1_Complex.html
華夏公益教科書