AoZai
AoZai

Reading Notice

These are personal study and translation notes for reference only; the original course materials belong to MIT OpenCourseWare and their respective rights holders.

MATLAB Tutorial

Basic Commands for Linear Algebra — MIT 18.06 · Ch.1 / 1

MATLAB Tutorial -- MIT 18.06 Linear Algebra

Introduction

MATLAB works constantly with matrices. A small number of basic commands lets you create vectors and matrices, change them, and operate with them.

Creating and Using Matrices -- Quick Example

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

Produces:

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

Produces:

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

Produces:

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

Produces:

[1]
[0]
[5]

Inverting a Matrix and Solving a Linear System

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

Produces:

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

Produces:

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

Produces (in decimal, normally; use format rat for fractions):

[ 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

Both produce x = [0; 0; 1] (since b is the third column of A, the solution is the third standard basis vector).

The \ (backslash) operator uses Gaussian elimination when A is square and never computes the inverse matrix.


Comments

% The comment symbol is the percent sign
% The symbols a and A are different: MATLAB is case-sensitive
  • Type help slash for a description of how to use the backslash symbol. The word help can be followed by a MATLAB symbol, command name, or M-file name.
  • The command name shown by help is uppercase, but must be lowercase in actual use.
  • The backslash A \ b behaves differently when A is not square.
  • To display all 16 digits, type format long. The default format short gives 4 digits after the decimal.
  • A semicolon after a command suppresses display of the result. For example, A = ones(3); will not display the 3x3 matrix.
  • Use the up-arrow cursor to return to previous commands.

How to Input a Row or Column Vector

% 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]

How to Input a Matrix (a Row at a Time)

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

Produces:

[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

Produces:

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

How to Create Special Matrices

% 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))

How to Change Entries in a Given Matrix 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

How to Create Submatrices of an m x n Matrix A

Command Result
A(i, j) The (i,j) entry (a scalar, i.e., a 1x1 matrix)
A(i, :) The ith row (as a row vector)
A(:, j) The jth column (as a column vector)
A(2:4, 3:7) Rows 2 through 4 and columns 3 through 7 (as a 3x5 matrix)
A([2 4], :) Rows 2 and 4, all columns (as a 2 x n matrix)
A(:) One long column formed from all columns of A (an mn x 1 matrix)
triu(A) Upper triangular part (sets entries below the main diagonal to zero)
tril(A) Lower triangular part (sets entries above the main diagonal to zero)

Matrix Multiplication and Inversion

Command Description
A * B Matrix product AB (if dimensions are compatible)
A .* B Entry-by-entry (element-wise) product (if size(A) == size(B))
inv(A) Inverse A^(-1) if A is square and invertible
pinv(A) Pseudoinverse of A
A \ B Left division -- computes inv(A) * B without explicitly inverting
x = A \ b Solves Ax = b if inv(A) exists (uses Gaussian elimination)

Important: See help slash for details when A is a rectangular matrix.


Numbers and Matrices Associated with A

Command Description
det(A) Determinant (if A is square)
rank(A) Rank (number of pivots = dimension of row space and column space)
size(A) Returns [m n] -- the dimensions of A
trace(A) Trace = sum of diagonal entries = sum of eigenvalues
null(A) A matrix whose n - r columns form an orthogonal basis for the nullspace of A
orth(A) A matrix whose r columns form an orthogonal basis for the column space of A

Examples

% 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

Built-in M-files for Matrix Factorizations (All Important!)

% 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

Creating M-files

M-files are text files ending with .m that MATLAB uses for functions and scripts.

  • A script is a sequence of commands executed when the file name is typed at the MATLAB prompt. MATLAB's demos are examples of scripts (e.g., the demo called house).
  • Most of MATLAB's built-in functions are actually M-files and can be viewed by typing type xxx where xxx is the function name.
  • To write your own scripts or functions, create a new text file with any name ending in .m.
  • A script file is simply a list of MATLAB commands.
  • For an M-file to be a function, it must start with the keyword function, followed by the output variables in brackets, the function name, and the input variables.

Example 1: mult.m

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

Save as mult.m. This function takes a matrix A and returns only the matrix product C. The variable r is not returned because it was not listed as an output variable. The semicolons suppress output to the MATLAB window -- useful when dealing with large matrices.

Example 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

This function takes matrix A as input and returns the eigenvector matrix, eigenvalue matrix, and rank as outputs. The % is used for comments. The function checks if the input matrix is square.

  • Typing properties(A) returns only the first output, V (the matrix of eigenvectors).
  • You must type [V, D, r] = properties(A) to get all three outputs.

Keeping a Diary of Your Work

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

Old diary files can be viewed using a text editor, printed with lpr in Unix, or viewed in MATLAB using the type filename command.


Saving Your Variables and Matrices

The diary command saves commands and output, but does not save the content of variables and matrices.

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 files are different from .m files (which are scripts or functions).


Graphics

Basic Plotting

plot(x, y)           % Plots points (xi, yi) connected by solid lines
  • x and y must be vectors of the same length.
  • If no x vector is given, MATLAB assumes x(i) = i. So plot(y) has equal spacing on the x-axis: points are (i, y(i)).

Line Style and Color

The type and color of the line can be changed by a third argument. The default is a solid black line.

% 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, ':')

Discrete Points (No Lines)

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

Multiple Graphs

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

Logarithmic Scales

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

Axis Scaling and Labels

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 Command

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

Printing and Saving

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

Based on the MATLAB tutorial from MIT 18.06 Linear Algebra, Spring 2010.

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