Using MATLAB For Linear Algebra
Using MATLAB For Linear Algebra
This is a collection of basic information and techniques for using MATLAB to explore matrix
properties, manipulations, and identities. These only address “numerical” (x is a particular number
or vector of numbers or matrix of numbers) rather than “symbolic” (x is a variable without any
particular value) functions of MATLAB.
2. Complex Numbers
√
a. Cartesian form. You can use either i or j for −1 (since we’re in a physics class,
we’ll use i exclusively). If i appears in a numerical expression, MATLAB will simply
interpret the number as a complex number. For example, if we want to set z equal to
3 + 4i, simply type it in this way:
>> z = 3 + 4*i
We could even omit the * in this case, but it is best to leave it in, since we need it if we
are using a variable such as y:
1
>> x = 1/sqrt(2);
>> y = -1/sqrt(3);
>> z = x + i*y
We can use any of the standard functions (e.g., exponentials or trigonometric functions)
directly. For example,
>> sin(1-sqrt(2)*i)
ans = 1.8329 - 1.0455i
Note that the answer comes back in standard x + yi form with decimals (as opposed to
fractions or explicit π’s).
b. Polar form. If we want to enter a number in the form reiθ , we just use the exp function:
>> r = 1;
>> theta = pi/6;
>> z = r*exp(i*theta)
z = 0.8660 + 0.5000i
>> conj(2-3*i)
ans = 2.0000 + 3.0000i
e. Real and imaginary parts. The functions real and imag do the trick:
Note that you always end up with the decimal version of numbers.
f. Modulus and angle. You can find r and θ using the abs and angle functions:
>> z = 2 * exp(i*pi/4)
z = 1.4142 + 1.4142i
>> abs(z)
ans = 2
>> angle(z) % answer should be pi/5 = 0.7854
ans = 0.7854
2
3. Creating Vectors and Matrices and Accessing Elements
Both vectors and matrices are specified by entries between [ ]’s with semicolons ; used to
separate rows. So
1 −2 1 3
A = 2 −5 4
B= 4
C= 3 4 5
−1 3 −2 5
are entered as
>> A = [1 -2 1; 2 -5 4; -1 3 -2]
A =
1 -2 1
2 -5 4
-1 3 -2
>> B = [3; 4; 5]
B =
3
4
5
>> C = [3 4 5]
C =
3 4 5
>> A(1,2)
ans = -2
>> A(2,2)
ans = -5
The nth row is A(n,:) and the mth column is A(:,m). So the 2nd row and 3rd columns are:
>> A(2,:)
ans =
2 -5 4
>> A(:,3)
ans =
1
4
-2
3
4. Special Matrices
a. For a 3 × 3 unit matrix, use eye(3) while for N × N use eye(N).
b. zeros(N) is an N × N matrix of zeros while zeros(1,N) is an N -dimensional row vector
of zeros and zeros(N,1) is an N -dimensional column vector of zeros.
c. ones(N) is an N × N matrix of ones while ones(1,N) is an N -dimensional row vector
of ones and ones(N,1) is an N -dimensional column vector of ones.
d. Random matrices. Use rand(N) to generate an N × N matrix whose entries are
random numbers uniformly distributed between 0 and 1. E.g.,
>> M = rand(3)
M =
0.1239 0.4238 0.0785
0.7745 0.1592 0.7084
0.1123 0.2949 0.0181
The numbers are really “pseudo-random” numbers. See help rand for more info. To
generate a uniform distribution of random numbers on a specified interval [a,b], multiply
the output of rand by (b-a), then add a. For example, to generate a 5-by-5 array of
uniformly distributed random numbers on the interval [10,50],
>> M = randn(3)
M =
-0.0956 -1.3362 -0.6918
-0.8323 0.7143 0.8580
0.2944 1.6236 1.2540
4
5. Matrix Operations
a. Matrix multiplication. Ordinary matrix multiplication is performed by using *. In
contrast, .* is used for element-by-element operations (e.g., A*B is matrix multiplication
while A.*B multiplies each element in A by the corresponding one in B).
b. Inverse of a matrix. The inverse of the square matrix A is designated A−1 and is
defined by AA−1 = A−1 A = I, where I is the identity matrix. We can find the inverse of
a matrix either by raising A to the −1 power, i.e., A^(-1), or with the inv(A) function.
c. Determinant of a matrix. The det function returns the determinant of a square
matrix. That is, det(A) gives the determinant of the matrix A.
d. Exponential of a matrix. The expm function returns the exponential of a matrix,
as defined by its Taylor series. So expm(A) gives eA . [Note: if you use exp(A) by
mistake (no m at the end of the name), you’ll get a matrix whose elements are each the
exponential of the corresponding matrix element in A.]
e. General matrix functions. To calculate the cosine, sine, or logarithm or a matrix A,
use funm(A,’cos’), funm(A,’sin’), or funm(A,’log’).
f. Trace of a matrix. The sum of the diagonal matrix element of matrix A is trace(A).
g. Adjoint and transpose of a matrix. The adjoint of matrix A (designated A† ),
which is the complex conjugate of the transpose, is found from A’ or the function
ctranspose(A). If you want just the transpose AT of A and not the complex conju-
gate, use A.’ or transpose(A).
h. Eigenvalues and eigenvectors of a matrix. E = eig(A) gives a vector with the
eigenvalues of the matrix A. [V,D] = eig(A) gives a diagonal matrix D of eigenvalues
and a matrix V whose columns are the corresponding eigenvectors.
The nth row of M is M(n,:) and the mth column is M(:,m). So the eigenvector v1 and
eigenvalue λ1 are (using random normally distributed matrix M from above.)
>> [V D] = eig(M)
V =
0.5736 0.4791 -0.4836
0.6074 -0.5096 0.5685
-0.5495 0.7147 0.6655
D =
-0.8479 0 0
0 0.2937 0
0 0 2.4269
>> v1 = V(:,1)
v1 =
0.5736
5
0.6074
-0.5495
>> lambda1 = D(1,1)
lambda1 = -0.8479
We can verify that M v1 = λ1 v1 :
>> M*v1
ans =
-0.4863
-0.5150
0.4660
>> lambda1*v1
ans =
-0.4863
-0.5150
0.4660
i. Powers of Matrices. To get A3 , just use A^3, and so on.
j. Bra’s and ket’s. We associate the “ket” |V i (or |1i or whatever) with a column vector.
The “bra” hV | is the adjoint of |V i, i.e., hV | = (|V i)† . Then hV |W i is simply the inner
product, which is a generalized dot product. Note that hW |V i = hV |W i∗ . Examples:
6
0.5547
0 + 0.8321i
>> Vket_unit = Vket/norm(Vket) % an easier way
Vket_unit =
0.5547
0 + 0.8321i
l. Isolating the Diagonal Elements. If M is a square matrix, then diag(M) is a vector
with the matrix elements on the main diagonal. E.g., for the normally distributed
random matrix M :
>> diag(M)
ans =
-0.0956
0.7143
1.2540
To cube each diagonal element, use diag(M).^3 (note the “.” before the ^). To get
a square matrix of the same size as M but with just it’s diagonal elements and zeros
elsewere, use diag(diag(M)).
m. Random Hermitian matrices. Generate a random complex matrix A and then a
random hermitian matrix by H = (A + A† )/2.
n. Random Unitary matrices. Generate a random Hermitian matrix H as above and
then U = eiH is unitary (so U U † = I). Use the MATLAB matrix exponentiation
function expm.
>> M = rand(100);
>> tic; det(M); toc
Elapsed time is 0.130749 seconds.
7. Condition Number
To find the condition number of a matrix, use cond(M). A number near one is good; if the
number is large the matrix is ill-conditioned. See the help for svd and gsvd to learn about
(generalized) singular value decomposition.
7
8. Solving Matrix Equations
Suppose we want to solve the simultaneous equations
3x − 2y = 17
5x + 3y = 3
We write this in the form M X = B, with M a matrix and B a column vector, then find the
desired column vector X from X = M −1 B using the MATLAB inv function:
8
a. % is used to mark a comment to help explain what the program is doing (or supposed to
do!). Everything on a line after a % is ignored. Examples:
% This is a comment line only; no MATLAB instructions.
height = 5 % This comment might say that height is in meters
b. A semicolon ; is used at the end of a line to suppress extra output from MATLAB,
which might be distracting.
c. input is used to get a value from the user for a variable. The general form is:
variable_name = input(’message to be displayed’)
For example,
radius = input(’Enter the radius of a circle: ’);
d. disp is used for output of a message (in the form of text enclosed in single quotes) or
the value of a variable. For example,
disp(’The area is: ’)
disp(area)
e. A MATLAB function is like a script but it starts with a function declaration with a
list of outputs between []’s, then an =, then the name of the function (same as the
filename), then the list of inputs in ()’s. Example:
function [area] = circle_area (radius)
which takes radius as input and returns area.
a. To plot sin x from −π to +π, we first define a set of points to plot, in the form of a
vector (which is considered a 1 × N matrix by MATLAB). We can specify a set of evenly
spaced points with spacing 0.1 by:
x = -pi:0.1:pi
To avoid seeing this vector printed out, add a semicolon to the end:
x = -pi:0.1:pi;
If instead we want a specified number of points (say 100), then
x = linspace(-pi,pi,100);
will do (“linspace” is short for “linear space”).
b. Then we give the x vector and the function to plot as the y vector to the plot command:
plot(x,sin(x))
which should pop up a figure window or make a new plot in an existing window (which
may be hidden by other windows). This function makes a regular linear-linear plot.
c. To add a second curve to the same graph (e.g., of cos x in the same range), use:
line(x,cos(x))
9
d. To make a log-log plot instead, we will typically want to space the points logarithmically
rather than linearly. To set x equal to 150 points from 10−5 to 102 , we can use
x = logspace(-5,2,150);
To plot x2 e−x from 10−10 to 101 with 200 points:
x = logspace(-10,1,200);
loglog(x,x.^2.*exp(-x))
Note that we use .^ and .* rather than ^ rather than *. The “.” means to exponentiate
or multiply (or divide, etc.) each term in the vector x, rather than trying to operate on
entire vectors or matrices. If you forget the “.” you’ll get an error message.
% Set a grid X Y with the desired range (and 20 points on each axis)
[X Y] = meshgrid( linspace(-2,2,20), linspace(-2,2,20) );
10