Matlab Quick Reference

advertisement
Matlab Quick Reference
Ali Habibnia - LSE
Ways to get help
help command
doc command
lookfor ...
docsearch ...
demo
which command
Display help text in command window.
Display documentation for function.
Search all M-files for keyword.
Search documentation for keyword.
Access demonstration examples.
Locate functions.
File extensions
.m
.mat
.fig
.p
.mex
Common object types
Single value 1 × 1 array.
Row or col matrices.
Arrays of 2+ dimensions.
Structure array.
Multidim arrays of mixed object types.
Used for object design.
Data import/exports
xlsread/xlswrite
readtable/writetable
dlmread/dlmwrite
fopen/fclose
fprint
disp
load/save -ascii
load/save
imread/imwrite
save filename
save filename x,y
load filename
urlread(URL)
inputdlg
Spreadsheets (.xls,.xlsm).
Create and write table.
ASCII delimited file.
Open/close file.
Write formatted data to file.
Display string or array.
Text files (txt,csv).
Matlab files (.m).
Image files.
Saves all variables to .mat file.
Saves x,y variables to .mat file.
Loads all variables from .mat file.
Download URL content to Matlab.
Dialog box that gathers user input.
Some basic commands
clc
clear
clear x
close all
whos x
ver
dir
beep
ans
pwd
mkdir
exit
x = 5
j:k
j:i:k
linspace(a,b,n)
NaN(a,b)
ones(a,b)
zeros(a,b)
eye(a)
rand(a,b)
randn(a,b)
diag(x)
Define variable x to be 5.
Row vector from j to k (step size 1).
Row vector from j to k (step size i).
n points linearly spaced between a & b.
a × b matrix of NaN values.
a × b matrix of 1 values.
a × b matrix of 0 values.
Identity matrix of size a.
Uniform random numbers in [0,1).
Gaussian random (center 0, variance 1).
Square matrix (diagonal is vector x).
Matrix Operations
A Matlab script, function, or class.
A Matlab data, stores workspace.
Matlab figure or GUI template.
Matlab protected function file.
Matlab executable.
scalar
vector
matrix
struct
cell/array
class
Defining variables
Clear command window.
Clear variables and functions.
Clear x from memory.
Close all figures.
size, bytes, class and attributes of x.
Lists version and toolboxes.
Lists folder content.
Makes the beep sound.
Last result.
Current directory.
Make new directory.
Close Matlab.
x=[1, 2, 3]
x=[1; 2; 3]
A=[1, 2; 3, 4]
inv(A)
size(A)
eig(A)
svd(A)
norm(A)
rank(A)
chol(A)
sort(A)
x.*y
x+y
A^n
A.^n
A’
1 × 3 (Row) vector.
1 × 3 (Column) vector.
2 × 2 matrix.
Inverse of matrix.
Size (rows and columns) of matrix.
Eigenvalues and eigenvectors.
Singular values.
Norms.
Rank.
Cholesky factorization of matrix.
Sorts vector from smallest to largest.
Element by element multiplication.
Element by element addition.
normal/Matrix power of A.
Elementwise power of A.
Transpose.
Plotting & Figures
plot(y)
plot(x,y)
plot(x,f(x))
loglog(x,y)
semilogx(x,y)
semilogy(x,y)
fplot(@(x) ,[a,b])
axis equal
title(’A Title’)
xlabel(’blah’)
ylabel(’blah’)
legend(’x1’,’x2’)
grid on/off
figure
subplot(a,b,c)
datetick(’x’,yy)
plot3
surf(x,y,z)
mesh(x,y,z)
hist(y)
hold on/hold off
Plot y, with 1,2,3,... as the x axis.
Plot y versus x (have same length).
If f is a function, plot the points.
Logarithmic x and y axes.
Logarithmic x axis.
Logarithmic y axis.
Plot a function.ezplot().
Force axes to be scaled equally.
Add a title at the top of the plot.
Label the x axis as blah.
Label the y axis as blah.
Label 2 curves in the plot x1 and x2.
Include a grid in the plot.
Open up a new figure window.
For multiple figures in single plot.
Time series axis.
A three-dimensional analogue of plot.
3-D colored surface Plot.
3-D mesh surface.
Histogram.
Allows or prevents plotting on
the same graph.
Programming
Scripts vs. Functions
Accessing/Assignment Elements
if x is a vector:
x(i)
x(i:j)
x(i:end)
x(:)
if A is a matrix:
A(i,j)
A(a:b,c:d)
diag(A)
find(A>5)
find(isnan(A))
A(i,j) = a
A(i,:) = []
A(A>100) = 0
Element i-th of x.
Elements from the i-th to the j-th of x.
Elements from the i-th to the last one of x.
All the elements of x.
Element i,j of A.
Elements in rows from a to b which are in
columns from c to d.
Elements in the principal diagonal of A.
Indices of elements ¿5.
Indices of NaN elements.
Replace element i,j of A with a.
Delete i-th row of A.
Replace all elements over 100
Script M-files: contain a list of commands that Matlab
simply executes in order. They are useful to batch simple
sequences of commonly used commands together.
Function M-files: can be executed by specifying some inputs
and return some desired outputs.
User defined functions
Function m-files:
function [out1,out2] = fun_name (in1,in2)
...
end
Numerical operations
if x is a vector:
sum(x)/prod(x)
min(x)/max(x)
mean(x)/var(x)
diff(x,k)
sqrt(x)
exp(x)
log(x)/log10(x)
Sum and product of the elements of x.
maximum and minimum of elements of x.
Mean and variance of the elements of x.
Successive k-differences of x..
Square root of each elements of x.
Exponential of each elements of x.
Natural logarithm and decimal log.
Anonymous functions: Matlab functions produced at the
command line. @ operator creates a function handle.
f = @(x)(x.^2+exp(x))
i.e. f(2)
Flow Control
Errors
vector or matrix into a compartment that it does not fit in.
if Statement Syntax: An if statement can be followed
by an (or more) optional elseif... and an else statement,
which is very useful to test various condition.
Common Errors
Handling Errors
Error using * Inner matrix dimensions must agree.
The * operator performs matrix multiplication, where an NxM
matrix is multiplied by an MxP matrix, resulting in an NxP
matrix. Use .* instead of * to perform the elementwise
multiplication.
Index exceeds matrix dimensions.
This error arises when you try to reference an element that
doesnt exist. Some useful functions to check sizes and number
of elements are numel(), size(), and length().
The expression to the left of the equals sign is not a
valid target for an assignment.
This error message arises because of misuse of the = and ==
operators. The = operator does an assignment, and the ==
operator does a logical test for equality.
Subscripted assignment dimension mismatch.
This error message arises because of an attempt to assign a
error
warning
assert
try, catch
if
(Condition_1)
Matlab Commands
elseif (Condition_2)
Matlab Commands
else
Matlab Commands
end
while loop: Repeat the commands while COND holds.
while (condition)
Matlab Commands
end
for loop: Loop from a to b in steps of s, in the variable i.
for i=a:s:b
Matlab Commands
end
Display message and abort function.
Display warning message.
Search all M-files for keyword.
’try’ a statement, if it returns an error,
’catch’ it and do another statement.
c 2015 Ali Habibnia
Copyright http://personal.lse.ac.uk/habibnia/
Download