AoZai
AoZai

阅读声明

本页为个人学习整理与翻译笔记,仅供学习参考;原课程内容版权归 MIT OpenCourseWare 及相关权利方所有。

MATLAB 教程

线性代数基本命令 - MIT 18.06 · 第1章 / 1

简介

MATLAB 始终与矩阵(matrix)打交道。少数几个基本命令即可让您创建向量(vector)和矩阵(matrix)、修改它们以及对其进行运算。

创建和使用矩阵 -- 快速示例

% Create the 3x3 identity matrix
E = eye(3)

输出结果:

[1 0 0]
[0 1 0]
[0 0 1]
% Pick out column 1
u = E(:, 1)

输出结果:

[1]
[0]
[0]
% Reset the (3,1) entry to 5
E(3, 1) = 5

输出结果:

[1 0 0]
[0 1 0]
[5 0 1]
% Multiply E and u
v = E * u

输出结果:

[1]
[0]
[5]

求逆矩阵与求解线性方程组

% Create a matrix: ones(3) + eye(3)
A = ones(3) + eye(3)

输出结果:

[2 1 1]
[1 2 1]
[1 1 2]
% b is the third column of A
b = A(:, 3)

输出结果:

[1]
[1]
[2]
% Compute the inverse
C = inv(A)

输出结果(通常为十进制;使用 format rat 可显示分数形式):

[ 0.75  -0.25  -0.25]
[-0.25   0.75  -0.25]
[-0.25  -0.25   0.75]
% Solve Ax = b -- the slow way
x = inv(A) * b

% Solve Ax = b -- the fast way (backslash, uses Gaussian elimination, never computes inverse)
x = A \ b

两者均输出 x = [0; 0; 1](因为 bA 的第三列,解即为第三个标准基向量)。

A 为方阵时,\(反斜杠)运算符使用高斯消元(Gaussian elimination)且从不计算逆矩阵。


注释

% The comment symbol is the percent sign
% The symbols a and A are different: MATLAB is case-sensitive
  • 输入 help slash 可查看反斜杠符号的使用说明。help 后面可以跟 MATLAB 符号、命令名称或 M 文件名(M-file)。
  • help 显示的命令名称为大写,但在实际使用中必须为小写。
  • A 不是方阵时,反斜杠 A \ b 的行为有所不同。
  • 要显示全部 16 位数字,请键入 format long。默认的 format short 显示小数点后 4 位。
  • 命令后的分号会抑制结果输出。例如,A = ones(3); 将不会显示 3x3 矩阵。
  • 使用上箭头键可以返回到之前的命令。

如何输入行向量或列向量

% Row vector (1x3 matrix)
u = [2 4 5]

% Column vector (3x1 matrix) -- semicolons separate rows
v = [2; 4; 5]

% Column vector -- transpose of a row vector
v = [2 4 5]'
v = u'

% Row vector with unit steps using the colon operator
w = 2:5    % produces w = [2 3 4 5]

% Row vector with custom step size
u = 1:2:7  % produces u = [1 3 5 7]

如何输入矩阵(逐行输入)

% Semicolon separates rows
A = [1 2 3; 4 5 6]

输出结果:

[1 2 3]
[4 5 6]
% Multi-line input also works
A = [1 2 3
     4 5 6]

% Transpose
B = [1 2 3; 4 5 6]'   % A^T is A' in MATLAB

输出结果:

[1 4]
[2 5]
[3 6]

如何创建特殊矩阵

% Diagonal matrix from a vector
diag(v)           % Diagonal matrix with vector v on its diagonal

% Toeplitz matrices
toeplitz(v)       % Symmetric constant-diagonal matrix with v as first row and first column
toeplitz(w, v)    % Constant-diagonal matrix with w as first column and v as first row

% Matrices of ones and zeros
ones(n)           % n x n matrix of ones
zeros(n)          % n x n matrix of zeros

% Identity matrix
eye(n)            % n x n identity matrix

% Random matrices
rand(n)           % n x n matrix with random entries between 0 and 1 (uniform distribution)
randn(n)          % n x n matrix with normally distributed entries (mean 0, variance 1)

% Rectangular matrices
ones(m, n)        % m x n matrix of ones
zeros(m, n)       % m x n matrix of zeros
rand(m, n)        % m x n matrix with random uniform entries

% Same shape as an existing matrix A
ones(size(A))
zeros(size(A))
eye(size(A))

如何修改给定矩阵 A 中的元素

% Reset a single entry
A(3, 2) = 7       % Sets the (3,2) entry to 7

% Reset an entire row
A(3, :) = v       % Sets the third row to vector v

% Reset an entire column
A(:, 2) = w       % Sets the second column to vector w

% The colon (:) stands for "all" (all columns or all rows)

% Exchange rows
A([2 3], :) = A([3 2], :)   % Swaps rows 2 and 3

如何创建 m x n 矩阵 A 的子矩阵

命令 结果
A(i, j) i,ji,j 个元素(标量,即 1x1 矩阵)
A(i, :) 第 i 行(行向量形式)
A(:, j) 第 j 列(列向量形式)
A(2:4, 3:7) 第 2 至 4 行和第 3 至 7 列(3x5 矩阵)
A([2 4], :) 第 2 和 4 行,所有列(2 x n 矩阵)
A(:) 由 A 的所有列连接而成的一个长列(mn x 1 矩阵)
triu(A) 上三角部分(将主对角线以下的元素置零)
tril(A) 下三角部分(将主对角线以上的元素置零)

矩阵乘法与求逆

命令 描述
A * B 矩阵乘积 AB(如果维度兼容)
A .* B 逐元素乘积(element-wise product)(如果 size(A) == size(B)
inv(A) 逆矩阵(inverse)A^(-1),如果 A 是方阵且可逆
pinv(A) A 的伪逆(pseudoinverse)
A \ B 左除(left division)-- 计算 inv(A) * B 而不显式求逆
x = A \ b 求解 Ax = b(如果 inv(A) 存在,使用高斯消元)

重要提示:当 A 为矩形矩阵时,请参见 help slash 了解详情。


与 A 相关的数值与矩阵

命令 描述
det(A) 行列式(determinant)(如果 A 是方阵)
rank(A) 秩(rank)(主元个数 = 行空间和列空间的维数)
size(A) 返回 [m n] -- A 的维度
trace(A) 迹(trace)= 对角线元素之和 = 特征值之和
null(A) 一个矩阵,其 n - r 列构成 A 的零空间(nullspace)的一组正交基
orth(A) 一个矩阵,其 r 列构成 A 的列空间(column space)的一组正交基

示例

% Elementary elimination matrix
E = eye(4);
E(2, 1) = -3;
% E * A subtracts 3 times row 1 of A from row 2

% Augmented matrix
B = [A b];    % Creates the augmented matrix with b as an extra column

% Permutation matrix
E = eye(3);
P = E([2 1 3], :);   % Creates a permutation matrix

% Identity: triu(A) + tril(A) - diag(diag(A)) equals A

用于矩阵分解的内置 M 文件(全部重要!)

% LU decomposition: PA = LU
[L, U, P] = lu(A)

% Eigenvalues
e = eig(A)              % Returns a vector containing the eigenvalues of A

% Eigenvalues and eigenvectors: AS = SE
[S, E] = eig(A)         % E is a diagonal eigenvalue matrix, S is the eigenvector matrix
                        % If A is not diagonalizable (too few eigenvectors), S is not invertible

% QR decomposition: A = QR
[Q, R] = qr(A)          % Q is an m x m orthogonal matrix, R is an m x n triangular matrix

创建 M 文件

M 文件是以 .m 结尾的文本文件,MATLAB 将其用于函数(function)和脚本(script)。

  • 脚本 是在 MATLAB 提示符下键入文件名时执行的一系列命令。MATLAB 的演示程序就是脚本的示例(例如名为 house 的演示)。
  • MATLAB 的大多数内置函数实际上是 M 文件,可以通过键入 type xxx(其中 xxx 是函数名)来查看。
  • 要编写自己的脚本或函数,创建一个文件名以 .m 结尾的新文本文件。
  • 脚本文件就是 MATLAB 命令的列表。
  • 要使 M 文件成为函数,它必须以关键字 function 开头,后跟方括号中的输出变量、函数名和输入变量。

示例 1:mult.m

function [C] = mult(A)
r = rank(A);
C = A' * A;

保存为 mult.m。此函数接受矩阵 A 并仅返回矩阵乘积 C。变量 r 不会被返回,因为它未被列为输出变量。分号会抑制 MATLAB 窗口中的输出 -- 在处理大型矩阵时非常有用。

示例 2:properties.m

function [V, D, r] = properties(A)
% This function finds the rank, eigenvalues and eigenvectors of A
[m, n] = size(A);
if m == n
    [V, D] = eig(A);
    r = rank(A);
else
    disp('Error: The matrix must be square');
end

此函数以矩阵 A 为输入,返回特征向量矩阵、特征值矩阵和秩作为输出。% 用于注释。该函数检查输入矩阵是否为方阵。

  • 键入 properties(A) 仅返回第一个输出 V(特征向量矩阵)。
  • 必须键入 [V, D, r] = properties(A) 才能获得所有三个输出。

记录工作日志

diary('filename')    % Records everything in the MATLAB window to a text file
diary on             % Start recording
diary off            % Stop recording

旧的工作日志文件可以使用文本编辑器查看,在 Unix 中使用 lpr 打印,或在 MATLAB 中使用 type filename 命令查看。


保存变量和矩阵

diary 命令会保存命令和输出,但不会保存变量和矩阵的内容。

whos                 % Lists all variables and their matrix sizes
save('xxx')          % Saves all variables into file xxx.mat (MATLAB adds .mat extension)
load xxx             % Loads variables from xxx.mat back into MATLAB

.mat 文件不同于 .m 文件(后者是脚本或函数)。


图形

基本绘图

plot(x, y)           % Plots points (xi, yi) connected by solid lines
  • xy 必须是长度相同的向量。
  • 如果未提供 x 向量,MATLAB 默认 x(i) = i。因此 plot(y) 在 x 轴上等间距取点:点为 (i, y(i))

线型和颜色

线条的类型和颜色可以通过第三个参数改变。默认是黑色实线。

% MATLAB 5: red + markers and dotted line
plot(x, y, 'r+:')

% MATLAB 4: dashed line
plot(x, y, '--')

% MATLAB 4: dotted line
plot(x, y, ':')

离散点(无线条)

plot(x, y, 'o')      % Circles
plot(x, y, '+')      % Plus signs
plot(x, y, '*')      % Stars
plot(x, y, '.')      % Dots

多图叠加

% Two graphs on the same axes
plot(x, y, X, Y)

对数坐标

loglog(x, y)         % Both axes logarithmic
semilogy(x, y)       % y-axis logarithmic
semilogx(x, y)       % x-axis logarithmic

坐标轴缩放与标签

axis([a b c d])      % Scales graph to rectangle: a <= x <= b, c <= y <= d
title('Height of Satellite')
xlabel('Time in seconds')
ylabel('Height in meters')

Hold 命令

hold                 % Keeps the current graph while plotting a new one
                     % Repeating hold clears the screen

打印与保存

print -Pprintername  % Send to printer
print -d filename    % Save graphics window to a file

本文基于 MIT 18.06 线性代数课程,2010 年春季学期的 MATLAB 教程。

© MIT OpenCourseWare  |  18.06 Linear Algebra  |  Gilbert Strang  |  Spring 2010
ocw.mit.edu  ·  CC BY-NC-SA 4.0