Sei sulla pagina 1di 4

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
help cmd

list all commands and built-in variables


briefly describes the command based on the
header of the m-file.
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.

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, ...)

compare strings. The strings must be


identical for it to return true.
concatenate strings

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.

Strings and Common Escape Sequences


A string constant consists of a sequence of
characters enclosed in single-quote marks.
\\
a literal backslash.
\
a literal single-quote character.
\n
newline, ASCII code 10.
\t
horizontal tab, ASCII code 9.

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.

A{selection}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.
Selected Built-in Functions
IEEE infinity, NaN
Inf, NaN
NA
Missing value
ans
last result not explicitly assigned
eps
machine precision
pi

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

equal to X y . For non-full-rank systems,


this is equivalent to the least-squares
solution,
x^y
x.^y
-x
x
x.

(X X)
T

X y.

power operator
element by element power operator
negation
complex conjugate transpose
transpose

Comparison and Boolean Operators


These operators work on an element-by-element
basis. Both arguments are always evaluated.
x < y
true if x is less than y.
x <= y
true if x is less than or equal to y.
x == y
true if x is equal to y.
x >= y
true if x is greater than or equal to y.
x > y
true if x is greater than y.
x~=y
true if x is not equal to y.
x & y
true if both x and y are true.
x | y
true if at least one of x or y is true.
~bool
true if bool is false.
Note: if x and y are scalars than the usual
comparisons are performed. If x is a vector or matrix and y
is a scalar, then all entries must be fulfil the criterion.
Short-circuit Boolean Operators
Operators evaluate left-to-right. Operands are only
evaluated if necessary, stopping once overall truth value can
be determined. Operands are converted to scalars using the
all function.
x && y
true if both x and y are true.
x || y
true if at least one of x or y is true.
Operator Precedence
Table of MATLAB operators, in order of increasing
precedence.
; ,
statement separators
=
assignment, groups left to right
|| &&
logical OR and AND
| &
element-wise OR and AND
< <= == >= > !=
relational operators
colon
:
+ addition and subtraction
*/\ .* ./ .\
multiplication and division
.
transpose
- !
unary minus, logical NOT
^ .^
exponentiation
Control Statements
for i =range; commands; end; Execute commands
until the last entry of the range vector is
reached. This is MATLABs FOR loop.
while (condition); commands; end; Executes
commands until the condition is false. This
is MATLABs WHILE loop.
break
exits the innermost loop

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

Table 2: Common TeX Codes

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

Equations, ODEs, and Quadrature


For more information about all the options and
required parameters for these functions refer to manuals or
more involved MATLAB summaries.
fsolve()
solves nonlinear algebraic equations.

solves nonlinear ordinary differential


equations. ID is any of the following tags:
23, 113, 15s, 23s, 23t, 23tb.
quad()
integrates nonlinear functions.
fminsearch(f,xo)
Calculates the minimum
of the function, f,based on an initial
guess, xo. The function can be an M-file.
The output from the function must be a
scalar. Thus, a vector funtion can be
converted to a scalar by taking the normal
of the function. However, the values should
have a similar magnitude or else the value
obtained may not 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.
feval(Mfilename,x1,x2,,xn) or
feval(handlef, x1,x2,,xn)
Evaluates an M-file using the variables
given after the file name. There must be as
many variables as is necessary. The
difference between the two forms lies in the
manner in which the function is presented.
In the first case, the actual name of the
M-file is known, while in the second the
variable, handlef, stores the name of the
function.
Polynomials
Polynomials are stored as a vector consisting of the
coefficients in decreasing powers of x. The vectors
containing the coefficients of the generic polynomials will be
referred to as p and q.
conv(p, q) computes the convolution of 2
polynomials.
deconv(p, q) computes the deconvolution of 2
polynomials (long division of a by b).
r=poly(p)
create a polynomial from the co-efficient
vector.
polyval(r, x) computes the value of the polynomial, r,
at a vector value of x.
polyvalm(r, X) computes the value of the polynomial,
r, for a matrix (or set) of values X.
roots(r)
finds the roots of the polynomial, r.
residue(p, q) finds the partial fraction decomposition
of the ratio p / q.
odeID()

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.
fprintf(fid, string,variables)
sends
formatted output to the file with
identification given by fid. The string
contains the text and formatting desired,
while variables is a vector containing the
data to be formatted.
sprintf(fid, string, variables)
sends
formatted output to a string
fgetl(fid) reads a line of text from the file with
identification, fid.
fgets(fid, len)
reads len characters from the
file with identification, fid.
ftell(fid)
returns the file pointer position for the
given file identification number, fid.
frewind(fid) moves the file pointer to the beginning of
the file with the given file identification
number, fid.
fread(fid, size, prec) reads binary data files
fwrite(fid, size, prec) writes binary data files
feof(fid)
returns if the pointer is at EOF (end of file).
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, takes
the data from the given spreadsheet name,
sheetname, and then stores all
numerical data in A and all text data in B.
Symbolic Math
Matlab can perform symbol math using the Maple
kernel. The symbolic variables are declared as using the
syntax >>syms var1 var2 condition, where
condition is any of the following:
a) real this limits the variable to only be in the real
domain, that is, R .
b) positive this limits the variable to only be
positive, that is, 0.

c) negative this limits the variable to only be


negative, that is, 0.
d) unreal this undoes any of the above 3 statements
and allows the variable to include complex numbers.
Generally, 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 then
once in order to truly simplify the results.
pretty(expression) displays the results in a nice
format.
sets the precision for the evaluation of a
digits(n)
symbolic expression to n-digits.
evaluates an expression to the
vpa(expression)
speficied precision.
subs(expression,{variable1,variable2
}, {value1,value2}) Replaces all
instance of variable1 with value1,
which can be another variable and so on.
jacobian(v, [x y z]) calculates the Jacobian of the
vector function, v, which is entered as a
column vector, and the independent
variables, x, y, and z. It should be noted
that the vector function need not be directly
a function of the variables desired. The
chain rule will, if necessary, be applied.
diff(f,variableWRT,n) calculates the nth order
derivative 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 of
the integral from a to b.
dsolve(f)
Solves algebraically the differential
equation, f.
Algebraically solves the equation, f.
solve(f)
Statistics
computes the correlation
corrcoef(x, y)
coecient for the data.
cov(x, y)
computes the covariance.
mean(a)
determines the mean value.
median(a)
determines the median value.
std(a)
determines the standard deviation.
var(a)
determines the variance.

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.

Potrebbero piacerti anche