reference card matlab
DESCRIPTION
Matlab Reference CardTRANSCRIPT
MATLAB Quick Reference MATLAB 2007b 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 list all commands and built-in variables help cmd briefly describes the command based on t
header of the m-file. he
apital
ay.
, t) compare strings. The strings must be
imit imit Specify a range of values
in ents
trings and Comm
ence of
aracter.
ex Expressicts the elements of a matrix, where
g:
A{selection}
Selected Built-inInf, NaNA M ng value
t explicitly assigned
lookfor str search for command based on str. Command-Line Cursor Motion ↑ scroll up through the command history. ↓ scroll down through the command history. HOME go to the start of a command line. END go to the end of the command line. Ctrl-← move backward a word. Ctrl-→ move forward a word. TAB complete a command or variable name. 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 cletter, 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.
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 arrfieldnames(F) returns the fields of a structure. Strings strcmp (s
identical for it to return true. strcat (s, t, ...) concatenate strings Ranges base:lbase:incr:l
beginn g with base with no elemgreater than limit. If it is omitted, the default value of incr is 1. Negative increments are permitted.
on Escape Sequences SA string constant consists of a sequ
characters enclosed in single-quote marks. \\ a literal backslash.
e ch\’ a literal single-quot\n newline, ASCII code 10.
e 9. \t horizontal tab, ASCII cod nd ons IA(selection)sele
selection can be any of the followin1) “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 secondcolumn; 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.
selects the elements of a cell array, 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 going to the end.
Functions IEEE infinity, NaN
issiNans last result noeps machine precision pi π
i or j 1− realmax maximum representable value rea ilmin m nimum representable value
x)= e ndexed
ments. y.
i
ltiplication
, this is
Assignment Expressions
xpr var = e assign expression to variable. var (id xpr assign expression to i
variable. var (idx) = [] delete the indexed ele
var {idx} = expr assign elements of a cell arra
emenArithmetic and Incr t Operators x+y addition x–y subtract on x*y matrix multiplication
ux.*y element by element mx/y matrix right division x./y element by element right division X\y left division. For a full-rank system
equal to 1X y− . For non-full-rank systems, res this is equivalent to the least-squa
solution, ( ) 1T TX X X y−
.
power operator element b wer operator negation
x^y x.^y y element po-x
tranx’ complex conjugate transpose x.’ spose
Comparison and Boolean Operators These operators work on an element-by
basi ments are always evaluated. -element
al to y.
usual ons are and y
e can rted to scalars using the
able of easing e.
ent separators
co
vision
T
cute commands ge vector is
hed. This is MATLAB’s FOR loop. xecutes
break
ndit cutes true.
ed.
ition n is
.
try; body;
Defining Functiist);
d outputs ist
or a
Function Handl@func @(var1, ...
nonymous function handles take opy of the variables in the current
func2str (h
error (messel.
lear pattern clear variables matching the given pattern string
ether str exists.
A are nonzero.
ices of the nonzero elements
umns
ns
he maximum value in each of the
an n-by-n diagonal matrix.
m) an n-by-m matrix of zeros.
m) es. [x,y]=size(A) e size of A, where x is the
er of
ts in A.
expm (A) atrix onential of A. - computes the -norm of the matrix, .
omputes the QR-factorisation of A.
f
dimen
s. Both argux < y true if x is less than y. x <= y x true if is less than or equal to y. x == y true if x is equal to y.
or equx >= y true if x is greater thanx > y true if x is greater than y.
y. x~=y true if x is not equal tox & y true if both x and y are true.
y is true. x | y true if at least one of x or ~bool true if bool is false.
Note: if x and y are scalars than the comparis performed. If x is a vector or matrix
l the criterion.is a scalar, then all entries must be fulfi Short-circuit Boolean Operators
Operators evaluate left-to-right. Operands are only evaluated if necessary, stopping once overall truth valube determined. Operands are conveall function. x && y true if both x and y are true. x || y true if at least one of x or y is true.
PrecedOperator ence T MATLAB operators, in order of incr
precedenc; , statem= assignment, groups left to right || && logical OR and AND | & element-wise OR and AND < <= == >= > != relational operators : lon + - addition and subtraction */\ .* ./ .\ multiplication and di’ .’ transpose - ! unary minus, logical NO
xponent^ .^ e iation
rol StatemeCont nts efor i =range; commands; end; Ex
until the last entry of the ranreac
while (condition); commands; end; Ecommands until the condition is false. Thisis MATLAB’s WHILE loop. exits the innermost loop
return return to the calling function. if (condition); commands; end;
executes the commands if the condition is true.
if (co ion); commands1; else;execommands2; end;
commands1 if the condition is Otherwise, commands2 is execut
if (condition1); commands1; elseif (condition2); commands2;…; else; commandsE; end executes commands1 if the first cond
itiois true. Otherwise, the second condtested and if true commands2 is executedThis can be continued, with the final conditions ending in an “else” and then thecommandsE will be executed if none of the conditions are satisfied. catch; cleanup; end; executes the body. If the body fails, the code in clean-up is executed.
ons tList]=fctName(argLfunction [oufunction-body; return; defines a function, called fctName,
ch has inputs argList anwhioutList. Both outList and argLcan be empty, contain a single variable, contain a list of variables separated bycomma.
es defines a function handle to func. ) expr defines an anonymous function handle. Aa cworkspace.
str2func (str) creates a function handle from astring. andle) 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
func. args to
Miscellaneous Functions eval(str) evaluates a string, str, as a command.
age) prints the error message and returns to top lev
c
exist(str) checks whrem(x, y) finds the remainder of x divided by y. Basic Matrix Manipulations
urns throws(A) ret e number of rows in A. columns(A) return the number of columns in A. all(A) checks if all the elements of any(A) checks if any of the elements in A are
nonzero. find(A) returns the ind
of A. sum(A) sums the elements in each of the col
of A. prod(A) finds the product of the elements of A. min(A) finds the minimum value in each colum
of A. max(A) finds t
columns of A. diag(n) creates eye(n) creates an n-by-n identity matrix.
, ones(n creates an n-by-m matrix of ones. zeros(n, m) creates rand(n, creates an n-by-m matrix of random valu
Determines thnumber of rows, and y is the numbcolumns in A.
length(A) Returns the total number of elemen Linear Algebra chol(A) Cholesky factorisation of A. det(A) computes the determinant of matrix, A. eig(A) computes the eigenvalues of A.
computes the m expinv(A) or A^ 1 inverts a square matrix, A. norm(A, p) p Aqr(A) crank(A) finds the rank of matrix A. svd(A) finds the singular value decomposition o
A. cross(x,y) Determines the cross product for two
3- sional vectors, x and y.
Signal Processing usfft(a) computes the Fast Fourier Transform ing
)
a and b
b.
t) h
will
plot3(x,y,,z,format) plots a 3-D graph using
string, which can be omitted, describes how ata will be plotted. Linear axes are
surf(x,y,z) x is
t
loglog(x,y, have a
le. hist(x) title(string)
ylabel(stri
plots t
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 (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
Plotting Functions plot(x,y,forma plots a 2-D graph using the data as
the point (x, y). The format string, whiccan be omitted, describes how the databe plotted. Linear axes are used.
the data as the point (x, y, z). The format
the dused. Creates a 3-dimensional graph, wherethe data for the x-axis, y is the data for they-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 poinand 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.
plots a 2-D graph simsemilogy(x,y,format) ilar to plot, except that the scale for the y-axis is logarithmic. format) plots a 2-D graph similarto plot, except that both axeslogarithmic scaplots a histogram of the data.
sets the plot title. xlabel(string) sets the x-axis label.
ng) sets the y-axis label. sets the zzlabel(string) -axis label
legend(array) sets the legend. The data in array is a cell array containing an entry for each of the data.
plays grid on dis grids on a plot.
grid off removes grids from a plot. hold on holds the current plot.
. hold off stops holding the current plotsubplot(r,c,w), plot() creates an array of
with r rows and c columns, with the currenplot being located at point w, which is an integer given by ( )1d dr c cw = − + , where
he matrix.
es
d is the desired position in t
Table 1: Common Plot Formatting Codforformat meaning mat meaning
b blue g green r red w white c cyan m magenta y yellow k black . point o (letter) circle x cross, + x-mark + * star, ✴ s square
d di amond, ◇ v ▽
^ △ < ◁
> ▻ p ☆ h h exagram - solid : dotted -. dash-dot -- dashed
on TeX Codes
TeX Table 2: Comm
TeX Display Display^ sup cript su ipt ers _ bscr{} gro ing \a ha up lp α
\beta β \g amma γ \d a \t ta elt δ he θ
\la da mb λ \mu μ \pi π \ o rh ρ
\sigma σ \tau τ \phi χ \chi \psi ψ \ omega ω \ circ ° \it italics \rm Roman \partial ∂
\nabla \pm \infty ∞ \bf b old
Equati DEs, an uadratu
ore info ation abo the op s and required meters f hese func refer to nuals or more inv MATLA ummariesfsolv solv onlinea raic
odeID solv linear ary dif al equa ns. ID is a the fo g tags: 23, , 15s, 23t, 2
unctionum
tion can be an M-file. a
e value
feval(‘Mfil
as
s lies in the
the name of the
Polynomials Polynom
coefficients in decontaining the co e referred to as p aconv(p, q)
deconv(p, q
ynomial from the co-efficient
r,
putes the value of the polynomial, X.
of the polynomial, r. osition
o OFor mns, d Q
rmor t
e
re ut all tion
para tions maolved B s . e() s n r algeb equations.
() es nontio113
ordinn f
ferentillowin3tb. s.
y o23s,
quad() integrates nonlinear ffminsearch(‘f’,xo) Calculates the minim
of the function, f,based on an initial guess, xo. The funcThe output from the function must be scalar. Thus, a vector funtion can be converted to a scalar by taking the normal of the function. However, the values should
e thhave a similar magnitude or elsay not obtained m be very accurate.
fzero(‘f’,xo) Determines a zero of the function f based on the initial guess xo. The function can be an M-file. ename’,x1,x2,…,xn) or feval(handlef, x1,x2,…,xn) Evaluates an M-file using the variables given after the file name. There must be many variables as is necessary. The difference between the two form
nner ima n which the function is presented. In the first case, the actual name of the M-file is known, while in the second
handlefvariable, , stores thefunction.
ials are stored as a vector consisting of the creasing powers of x. The vectors efficients of the generic polynomials will bnd q. computes the convolution of 2 polynomials. ) computes the deconvolution of 2 polynomials (long division of a by b). create a polr=poly(p) vector.
polyval(r, x) computes the value of the polynomial, at a vector value of x.
polyvalm(r, X) comr, for a matrix (or set) of values
roots(r) finds the roots residue(p, q) finds the partial fraction decomp
of the ratio p / q.
C-style Input and Output fid=fopen(name, mode) open a file in mode
located at name and stores its identification in fid.
fclose(fid closes the file with identification fid. )
n by fid. The string contains the text and formatting desired, while variables is a vector containing the
ormatted. s
fgetl(fid) le with
ftell(fid)
frewind(fid)
a files s file).
’)s e,
erical data in A and all text data in B.
ple kernel. The symb he
al
b) “positipositive, t
c) “negati be negative, t
d) “unreal the variable to include complex numbers.
hen s.
disp
di
vp
ble2’Replaces all
ly
r
solve(f) Statistics corrcoef(x,
median(a)
un (p p,
p,df)Calculates the inverse t-distribution at a bili degrees
nt =regress(b,a multiple
form Ax = b rs:
contains the 100(1-alpha)% confidence intervals for the coefficients; res a vector that contains
residuals; resint a vector for residual
at
s.
Ci=nlparci( s the
ue of
[y,delta]=n
Copyright ©2009
fprintf(fid, string,variables) sends formatted output to the file with identification give
data to be fsprintf(fid, string, variables) send
formatted output to a string reads a line of text from the fiidentification, fid.
fgets(fid, len) reads len characters from the file with identification, fid. returns the file pointer position for the given file identification number, fid. moves the file pointer to the beginning of the file with the given file identification
su
number, fid. fread(fid, size, prec) reads binary datfwrite(fid, size, prec) writes binary data filefeof(fid) returns if the pointer is at EOF (end of Other Input and Output functions save filename var1,var2,... saves variables
(var1, var2,…) in the file called, filename.
load filename loads the variables stored in the given file.
[A B] = xlsread(‘filename’,’sheetname Reads an Excel file, ‘filename’, takethe data from the given spreadsheet nam‘sheetname’, and then stores all num
Symbolic Math
Matlab can perform symbol math using the Maolic variables are declared as using t
ms var1 var2 conditionsyntax “>>sy ”, where condition is any of the following:
real is limits tha) “ ” th e variable to only be in the redomain, that is, ∈R .
ve” this limits the variable to only be hat is, ≥0.
ve” this limits the variable to only hat is, ≤0. ” this undoes any of the above 3 statements
and allowsGenerally, the same function can be used for symbolic math as for numerical math. The following are special functions: simplify(expression) simplifies a given
expression. It should be run more tonce in order to truly simplify the result
pretty(expression) lays the results in a nice format.
gits(n) sets the precision for the evaluation of asymbolic expression to n-digits.
a(expression) evaluates an expression to the speficied precision.
bs(expression,{‘variable1’,’varia}, {value1,value2}) instance of variable1 with value1, which can be another variable and so on.
calc of thejacobian(v, [x y z]) ulates the Jacobianvector function, v, which is entered as a column vector, and the independent
d variables, x, y, and z. It should be notethat the vector function need not be directa function of the variables desired. The chain rule will, if necessary, be applied.
diff(f,’variableWRT’,n) calculates the nth ordederivative of the function, f, with respect to the variable variableWRT.
int(f,’variable’,a,b) integrates symbolically the function, f, with respect to the variable, variable and determines the exact value ofthe integral from a to b.
dsolve(f) Solves algebraically the differential equation, f. Algebraically solves the equation, f.
y) computes the correlation coefficient for the data.
cov(x, y) computes the covariance. mean(a) determines the mean value.
determines the median value. std(a) determines the standard deviation. var(a) determines the variance.
Statistical Toolbox The following f ctions require the statistical toolbox.Z=norminv )Calculates the Z-score for probability
which lies between 0 and 1. X=tinv(
proba ty, p, given the number ofof freedom, df. ,res,resint,stats[coeff,Ci ]A,alpha) Computes linear regression model of the and returns the following parametecoeff a vector of the estimated coefficients; Cint vector that
the analysis; stats a vector with the following entries: R2-statistic assuming ththe 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-datais 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 valueThe function should allow matrix evaluation. The initial guess is given as beta0. beta contains the estimated coefficients, r contains the residuals, and Jis the Jacobian evaluated at final calculation. beta,r,J,alpha) Calculate100(1-alpha)% confidence intervals for the coefficients, beta, given the residuals,r, and the Jacobian, J. The default valalpha is 0.05. lpredci(‘Fun’, x, beta,r,J) Calculates the 100(1-alpha)% predictionconfidence 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-widthlengths, delta. Yuri Shardt. All rights reserved.