矩阵和数组

在 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]);