Reference Card MATLAB
Reference Card MATLAB
Starting MATLAB
matlab
start interactive MATLAB session
Stopping MATLAB
quit or exit exit MATLAB
Ctrl-C
stop current command and return to
top-level prompt.
Getting Help
help
help cmd
Multi-dimensional Arrays
Multi-dimensional arrays may be created with the
cat or reshape commands from two-dimensional
submatrices.
squeeze(A) remove the singleton dimensions of the
array.
ndims(A)
returns the number of dimensions in the
array.
Cells and Structures
F.field = ... set a field of a structure.
F{idx} = ... set an element of a cell array.
cellfun(F, c) apply a function to elements of cell array.
fieldnames(F)
returns the fields of a structure.
Strings
strcmp (s, t)
strcat (s, t, ...)
Ranges
base:limit
Specify a range of values
base:incr:limit
beginning with base with no elements
greater than limit. If it is omitted, the
default value of incr is 1. Negative
increments are permitted.
Shell Commands
cd dir
change the working directory to dir
pwd
print the working directory
ls
print the directory listing
getenv(string)
returns the value of the named
environment variable.
[status,result]=system(cmd)
executes
arbitrary shell command string, cmd, and
returns the status and the result of
the string.
Matrices
Square brackets delimit literal matrices. Commas
separate elements on the same row. Semicolons separate
rows. Commas may be replaced by spaces, and semicolons
may be replaced by one or more newlines. Elements of a
matrix may be arbitrary expressions, assuming all the
dimensions agree. Generic matrices will denoted as a capital
letter, for example, A. A vector, which is, either a row or
column matrix will be denoted by a lower case letter, for
example, x.
[x, y, ... ]
enter a row vector.
[x; y; ... ]
enter a column vector.
[w, x; y, z ]
enter a 2-by-2 matrix.
Index Expressions
A(selection)selects the elements of a matrix, where
selection can be any of the following:
1) 2,3 selects the entry located at the 2nd
row and 3rd column of the matrix; 2) 2
selects the second entry of a vector; 3)
a:b,2 selects the values in rows
between a and b and the second column; 4)
:,2 selects all the values in the second
column; 5) 4:end,2 selects all the
values in the second column and in rows
starting at the 4th row and continuing to the
end.
i or j
realmax
realmin
1
maximum representable value
minimum representable value
Assignment Expressions
var = expr assign expression to variable.
var (idx)= expr
assign expression to indexed
variable.
var (idx) = []
delete the indexed elements.
var {idx} = expr assign elements of a cell array.
Arithmetic and Increment Operators
x+y
addition
xy
subtraction
x*y
matrix multiplication
x.*y
element by element multiplication
x/y
matrix right division
x./y
element by element right division
X\y
left division. For a full-rank system, this is
1
(X X)
T
X y.
power operator
element by element power operator
negation
complex conjugate transpose
transpose
return
return to the calling function.
if (condition); commands; end;
executes the commands if the
condition is true.
if (condition); commands1; else;
commands2; end;
executes
commands1 if the condition is true.
Otherwise, commands2 is executed.
if (condition1); commands1; elseif
(condition2); commands2;;
else; commandsE; end
executes commands1 if the first condition
is true. Otherwise, the second condition is
tested and if true commands2 is executed.
This can be continued, with the final
conditions ending in an else and then the
commandsE will be executed if none of the
conditions are satisfied.
try; body; catch; cleanup; end;
executes the body. If the body fails, the
code in clean-up is executed.
Defining Functions
function [outList]=fctName(argList);
function-body; return;
defines a function, called fctName,
which has inputs argList and outputs
outList. Both outList and argList
can be empty, contain a single variable, or
contain a list of variables separated by a
comma.
Function Handles
@func
defines a function handle to func.
@(var1, ...) expr defines an anonymous function
handle. Anonymous function handles take
a copy of the variables in the current
workspace.
str2func (str)
creates a function handle from a
string.
func2str (handle) returns a string representation of
afunction handle.
handle (arg1, ...)
evaluates a function
handle.
feval (func, args)
evaluates a function
handle or string by passing the remaining
args to func.
Miscellaneous Functions
eval(str)
evaluates a string, str, as a command.
error (message)
prints the error message and
returns to top level.
clear variables matching the given
clear pattern
pattern string
exist(str) checks whether str exists.
rem(x, y)
finds the remainder of x divided by y.
Basic Matrix Manipulations
rows(A)
returns the number of rows in A.
columns(A) return the number of columns in A.
all(A)
checks if all the elements of A are nonzero.
any(A)
checks if any of the elements in A are
nonzero.
find(A)
returns the indices of the nonzero elements
of A.
sum(A)
sums the elements in each of the columns
of A.
prod(A)
finds the product of the elements of A.
min(A)
finds the minimum value in each columns
of A.
max(A)
finds the maximum value in each of the
columns of A.
diag(n)
creates an n-by-n diagonal matrix.
eye(n)
creates an n-by-n identity matrix.
ones(n, m) creates an n-by-m matrix of ones.
zeros(n, m) creates an n-by-m matrix of zeros.
rand(n, m) creates an n-by-m matrix of random values.
[x,y]=size(A)Determines the size of A, where x is the
number of rows, and y is the number of
columns in A.
length(A)
Returns the total number of elements in A.
Linear Algebra
chol(A)
Cholesky factorisation of A.
det(A)
computes the determinant of matrix, A.
eig(A)
computes the eigenvalues of A.
expm (A)
computes the matrix exponential of A.
inv(A) or A^-1
inverts a square matrix, A.
norm(A, p) computes the p-norm of the matrix, A.
qr(A)
computes the QR-factorisation of A.
rank(A)
finds the rank of matrix A.
svd(A)
finds the singular value decomposition of
A.
cross(x,y) Determines the cross product for two
3-dimensional vectors, x and y.
Signal Processing
fft(a)
computes the Fast Fourier Transform using
FFTW.
ifft(a)
computes the inverse FFT using FFTW.
freqz(args) computes the finite impulse response (FIR)
filter frequency response.
filter(a,b,x)
computes the filtered data based
on the filter transfer functions a and b
(which are given as polynomials in
decreasing powers of z or z-1) and the
original data, x.
conv(a,b)
finds the convolution of 2 vectors a and b.
Plotting Functions
plot(x,y,format) plots a 2-D graph using the data as
the point (x, y). The format string, which
can be omitted, describes how the data will
be plotted. Linear axes are used.
plot3(x,y,,z,format)
plots a 3-D graph using
the data as the point (x, y, z). The format
string, which can be omitted, describes how
the data will be plotted. Linear axes are
used.
surf(x,y,z) Creates a 3-dimensional graph, where x is
the data for the x-axis, y is the data for the
y-axis, and z is the data for the z-axis.
fplot(function,[l,u]) Plots a function over the
range [l, u], where l is the lower point
and u is the upper point of the region, so
that it appears correctly.
semilogx(x,y,format)
plots a 2-D graph similar
to plot, except that the scale for the x-axis is
logarithmic.
semilogy(x,y,format)
plots a 2-D graph similar
to plot, except that the scale for the y-axis is
logarithmic.
loglog(x,y,format)
plots a 2-D graph similar
to plot, except that both axes have a
logarithmic scale.
hist(x)
plots a histogram of the data.
title(string)
sets the plot title.
xlabel(string)
sets the x-axis label.
ylabel(string)
sets the y-axis label.
zlabel(string)
sets the z-axis label
legend(array)
sets the legend. The data in
array is a cell array containing an entry
for each of the data.
grid on
displays grids on a plot.
grid off
removes grids from a plot.
hold on
holds the current plot.
hold off
stops holding the current plot.
subplot(r,c,w), plot() creates an array of plots
with r rows and c columns, with the current
plot being located at point w, which is an
integer given by w = ( rd 1) c + cd , where
d is the desired position in the matrix.
Table 1: Common Plot Formatting Codes
format
b
r
c
y
.
x
*
meaning
blue
red
cyan
yellow
point
x-mark
star,
format
g
w
m
k
o (letter)
+
s
meaning
green
white
magenta
black
circle
cross, +
square
diamond,
<
>
h
:
--
hexagram
dotted
dashed
p
-.
solid
dash-dot
TeX
^
{}
\beta
\delta
\lambda
\pi
\sigma
\phi
\psi
\circ
\rm
\nabla
\infty
Display
superscript
grouping
Roman
TeX
_
\alpha
\gamma
\theta
\mu
\rho
\tau
\chi
\omega
\it
\partial
\pm
\bf
Display
subscript
italics
bold
Statistical Toolbox
The following functions require the statistical toolbox.
Z=norminv(p)Calculates the Z-score for probability p,
which lies between 0 and 1.
X=tinv(p,df)Calculates the inverse t-distribution at a
probability, p, given the number of degrees
of freedom, df.
[coeff,Cint,res,resint,stats]=regress(b,
A,alpha)
Computes a multiple
linear regression model of the form Ax = b
and returns the following parameters:
coeff a vector of the estimated
coefficients; Cint vector that contains the
100(1-alpha)% confidence intervals for
the coefficients; res a vector that contains
the residuals; resint a vector for residual
analysis; stats a vector with the
following entries: R2-statistic assuming that
the model contains a constant term; the
F-statistic for the full model; p-value for
the full model; and the estimated error
variance.
[beta,r,J] = nlinfit(x,y,FUN,beta0)
Performs non-linear regression. The x-data
is given as x, while the y-data is given as y.
The function, FUN that is to be fitted must
be written as an M-file that takes 3
arguments: x, y, and the coefficient values.
The function should allow matrix
evaluation. The initial guess is given as
beta0. beta contains the estimated
coefficients, r contains the residuals, and J
is the Jacobian evaluated at final
calculation.
Calculates the
Ci=nlparci(beta,r,J,alpha)
100(1-alpha)% confidence intervals for
the coefficients, beta, given the residuals,
r, and the Jacobian, J. The default value of
alpha is 0.05.
[y,delta]=nlpredci(Fun, x, beta,r,J)
Calculates the 100(1-alpha)% prediction
confidence intervals for the non-linear
function, Fun, given x, the estimated
coefficients, beta, the residuals, r, the
Jacobian, J. The function returns the
predicted y-values, y, and the half-width
lengths, delta.
Copyright 2009Yuri Shardt. All rights reserved.