矩陣和陣列

在 MATLAB 中,最基本的資料型別是數字陣列。它可以是標量,1-D 向量,2-D 矩陣或 ND 多維陣列。

% a 1-by-1 scalar value
x = 1;

要建立行向量,請在括號內輸入元素,用空格或逗號分隔:

% a 1-by-4 row vector
v = [1, 2, 3, 4];
v = [1 2 3 4];

要建立列向量,請使用分號分隔元素:

% a 4-by-1 column vector
v = [1; 2; 3; 4];

要建立矩陣,我們輸入以前用分號分隔的行:

% a 2 row-by-4 column matrix
M = [1 2 3 4; 5 6 7 8];

% a 4 row-by-2 column matrix
M = [1 2; ...
     4 5; ...
     6 7; ...
     8 9];

請注意,你無法建立行/列大小不相等的矩陣。所有行的長度必須相同,並且所有列的長度必須相同:

% an unequal row / column matrix
M = [1 2 3 ; 4 5 6 7]; % This is not valid and will return an error

% another unequal row / column matrix
M = [1 2 3; ...
     4   5; ...
     6 7 8; ...
     9   10];     % This is not valid and will return an error

為了轉置向量或矩陣,我們使用 .'-operator 或'運算元來取其 Hermitian 共軛,這是它的轉置的複共軛。對於真實矩陣,這兩個是相同的:

% create a row vector and transpose it into a column vector
v = [1 2 3 4].';              % v is equal to [1; 2; 3; 4];

% create a 2-by-4 matrix and transpose it to get a 4-by-2 matrix
M = [1 2 3 4; 5 6 7 8].';     % M is equal to [1 5; 2 6; 3 7; 4 8]

% transpose a vector or matrix stored as a variable
A = [1 2; 3 4];
B = A.';                      % B is equal to [1 3; 2 4]

對於超過二維的陣列,沒有直接的語言語法可以直接輸入它們。相反,我們必須使用函式來構造它們(例如 oneszerosrand)或者通過操作其他陣列(使用 catreshapepermute 等函式)。一些例子:

% a 5-by-2-by-4-by-3 array (4-dimensions)
arr = ones(5, 2, 4, 3);

% a 2-by-3-by-2 array (3-dimensions)
arr = cat(3, [1 2 3; 4 5 6], [7 8 9; 0 1 2]);

% a 5-by-4-by-3-by-2 (4-dimensions)
arr = reshape(1:120, [5 4 3 2]);