MatLab Tutorial
What is it:
- Mathematics program for performing scientific and engineering
calculations.
- Excellent tool for doing matrix manipulations and linear algebra.
- For more info, check out MIT's online help
Basics:
Help
- help topic: gives help on specified topic
- lookfor string: keyword search
- which function: locate functions and files
Line Editting
- CTRL-P Previous command
- CTRL-N Next command
- CTRL-A Beginning of command line
- CTRL-E End of command line
- CTRL-F Forward one character
- CTRL-B Back one character
- CTRL-K Delete line from cursor to end
- CTRL-D Delete next character
- CTRL-C Stop current command
Memory Management
- who list variables
- whos list variables and size
- clear varname removes variables, no arguments
removes all variables.
- save foo saves to foo.mat, default is matlab.mat
- load foo retrieves foo.mat
- pack garbage collection
- diary save text of matlab session
Constants
Matrix Manipulations
- A=[1 2 3; 4 5 6]
- A=[1 2 3
4 5 6]
- t=[1:10]
- t=[1:0.1:10]
- A(1,:) selects first row
- A(:,1) selects first column
- A(:) makes A into a column vector
- size(A) matrix dimensions
- zeros(M,N) MxN matrix of zeros
- ones(M,N) MxN maxtrix of ones
- eye(M,N) MxN identity matrix
Matrix Operations
- +-*/\
- x=A\b => Ax=b
x=b/A => xA=b
- ' transpose
- ^ power
- . element by element operations
Logical Relations
- <> <= >= == ~= & | ~(NOT)
- find returns indices of non zero elements
- any true if any element of a column vector is true
- all returns row vector of 1's and 0's indicating true or
false over column of array
Vector Operations
- Operates columnwise
- mean, sum, prod, max, min
- diff first difference
Math
- sin,cos, exp, log
- abs, angle
- log, log10
Plotting
- plot(t,x) i.e. t=[0:800]; x=cos(2*pi.*t*(200)/8000;
- stem
- hold freeze/unfreeze
- title
- xlabel
- ylabel
- axis
- clf
- figure
- close
- subplot
- legend(linetype, 'string', linetype2, 'string2')
- ginput(Npoints)
- gtext('string')
- text(x,y,'string')
- set(gca)
- set(gcf)
- orientportrait, landscape, tall
- print
Programming
Flow Control
- for i=1:n (something) end
- if (bool) (something) elseif (something) end
- nargin number of input arguments
- nargout number of output arguments
Functions
In fcn.m:
function z=fcn(x,y)
%comment
z=x+y;
Efficiency
- tic;toc
- tic;foo;toc
- flops
- flops(0);foo;flops
Inefficient:
function y=cclip(x,limit)
% clips
y=x;
for i=1:length(y)
if (abs(y(i))<limit)
y(i)=0.0;
end
end
Efficient:
function y=cclip2(x,limit)
% clips
y=x;
z=find(abs(y)<limit);
y(z)=zeros(size(z));
Signal Processing Functions
- filter(b,a,x) startup transients
- filtfilt(b,a,x) zero phase distortion, doubles
filter length
- fftfilt(b,x) similar to filter except uses fft,
good for short filter lengths and long signals.
- fft computes fft
- freqz(b, a, N, Fs) z transform digital filter
frequency response
- fir1(L, Wp, window) window based FIR design
Ona Wu
ona@nmr.mgh.harvard.edu
MGH-NMR Center
CNY-2301
13th Street, Bldg 149
Boston, MA 02129