Basic Computational Matlab

Constructing Matrices

A=[1 2 3 ; 4 5 6]
to define a 2 by 3 numerical matrix.
[m,n]= size(A)
to obtain the number of rows and columns of A.
l=length(x)
for the length of a vector.
A(2,1)=4
to assign the value 4 to the row 2, column 1 entry of A.
x=A(:,2) or x= A(1:2,2)
to assign the second column of A to the vector x.
x=reshape(A,6,1)
to convert the 2 by 3 matrix A to a 6 by 1 vector x.
A=reshape(x,2,3)
to convert the 6 by 1 matrix A to a 2 by 3 matrix A.
I=eye(3)
3 by 3 identity matrix.
I=zeros(3)
3 by 3 zero matrix.
A=diag(x)
construct a diagonal matrix from a list of entries.
A=[B C]
to construct a matrix out of the blocks B and C horizontally.
A=[B; C]
to construct a matrix out of the blocks B and C vertically.
x=[0:10:25]
to produce the vector [0 10 20]
pi, exp(1)
the transcendental constants.

Loading to and Saving from Files

load A.dat
to load the matrix A from an ASCII datafile named A.dat whose i'th row contains the i'th row of A separated by whitespace.
save A.dat A -ascii -double
to save the matrix A in the file A.dat.

Simple Operations

B = A*A
matrix multiplication.
B=A.'
transposing a matrix.
B=A'
conjugate transpose of a matrix.
C=A .* B
Multiplying each entry of A by the corresponsing entry of B.
x=inv(A) *b or x= A \ b
to solve the square linear system Ax=b.
vals=eig(A) or [P,D] =eig(A)
to get the eignevalues and eigenvectors of a matrix. (Vals is a vector, while P, and D are matrices.)
expm(A)
matrix exponential.
cond(A)
condition number.
rref(A)
reduced row echelon form.
subspace(A1,A2)
compute the angle between subspaces (assumed equal dimensional) spanned by columns of A1 and A2.
null(A)
an orthonormal basis for the nullspace of A.
orth(A)
an orthonormal basis for the range of A.
A=sparse(i,j,x)
construct a sparse matrix whose k'th nonzero entry is x(k) in position row i(k) col j(k) where i, j, and k are all vectors.

Looping and Conditionals

for j=1:3
      A(2,j)= j^2
end
to use a for loop to assign entries to the second row of a matrix.
if i > 1
      x=3
      y=5
else
      x=2
end
for conditionals. (There is also a keyword elseif.)
while i < 10
      A(i)=B(i)+1/i
end
for while loops.

Finding Roots And Polynoimials

roots(p)
finds the roots of a polynomial p, the polynomial being given in vector format. (Coefficients appear highest order first, lowest order last.)
fzero
fsolve
polyval
ppval
spline

Numerical Integration

quad('fcn',a,b)
numerically integrates the function defined in the m-file fcn.m from x=a to x=b.
dblquad('fcn',x0,x1,y0,y1))
is for double integration.
[t,x]=ode45('eqn_def',[t0 t1], x0)
will numerically integrate the differential equation defined in eqn_def.m from time t0 to time t1 with initial value x0.

Last Update: September 25, 2000

[Mathlab Home | Math]