Quick Refmaerence Guide Matlab
Quick Refmaerence Guide Matlab
May 2006 2006 Carolina Workshop on Force Measurement and Manipulation in Biological Microscopy
Matlab is a mathematics-friendly programming language used in the analysis and simulation of data. It has syntactical similarities to C, C++, and Java. This Quick Reference uses Matlab version 6.5 (R13).
Special Constants
ans eps NaN pi 3.14 most recent answer. smallest floating-point value possible. i.e. epsilon. Not-a-Number. i,j true false inf sqrt(-1) 1 0 infinity
Sizing Things
length size length of vector (1D). Size of n-dimensional array.
Manipulating Arrays
zeros ones repmat sort sortrows flipud concat rows concat cols select row delete row set row = 5 set col = 5 create an array of zeros. create an array of ones. replicate and tile an array. sort elements. sort rows by a column. flip matrices up-down. M = [m1 ; m2] M = [m1 m2] d = mymatrix(row,:); mymatrix(row,:) = [ ]; mymatrix(row,:) = 5; mymatrix(:,col) = 5;
Special Characters
% ! , . ; () single-line comment. encloses strings or matrix transpose. Runs OS-level program. Separates matrix column entries. Used in element-wise math ops or separates var names from fieldnames. Suppresses output, or marks end of row. reference elements of arrays. also used to alter standard order of operation. also encloses parameters during function call. encloses definition of matrix/array. define/reference elements of cell array.
Filename Extensions
.m .mat .fig .mex script or function file binary workspace file. Matlab figure or GUI template. Matlab-executable.
[] {}
Debugging Hints
dbstop set debugging stop. dbclear clear debugging stop. dbquit exit debug mode. Remove semicolons at the end of lines to print output to command window. Stick to one-function one-task philosophy. Comment your m-files thoroughly, including header comments for real-time help later. Use ellipses () to continue long lines of code to the next line. Try using functions instead of scripts to avoid mangling values of variables. Check for function name overloading. Making a variable named sum is a bad idea if you want to use the sum function later in your code. Use global variables only when necessary.
Strings
strcmp findstr strrep concatenate compare two strings. find string A within string B. replace string with another. mystring = [str1 str2];
Printing Output
disp fprintf display string or array. print formatted data to screen/ file.
Flow Control
if elseif else end if myarmy.size < yourarmy.size a = recruit_forces; elseif myarmy.size > yourarmy.size a = begin_invasion; else a = init_cheat_seq; end switch weekday case Monday mood = black; case Tuesday mood = blue; otherwise mood = green; end while (~weekend) work_hard_4_the_money(); end for k = 1 : 7 mysevens(k) = 7*k; end break out of while/for-loop. pass control to next iteration. wait for time-period or user response. stopwatch timer.
Function Input/Output
nargin nargout varargin varargout # of input arguments. # of output arguments. variable length input argument list as cell array. variable length output argument list as cell array.
Colon Operator
count a to b, by stepsize s. count 1-10 0-10, evens count down d = a:s:b; d = 1:10; d = 0:2:10; d = 10:-1:1;
Code Optimization
Vectorize code to speed up processing. Find ways around using for-loops or while-loops.
Testing Cases
exist isempty isnan isfield true if variable is defined. true for empty array. true for Not-a-Number. true if field exists in structure.
Anatomy of a function
function v = function_name(arg1, arg2) v = arg1 + arg2; return
find
Find is a useful function that searches within a variable without using for-loops. Find operates on a variable and returns the vector containing index values that match its conditional input. idx = find(q<10); q<10? my_q = q(idx); idx = find(foo == true); foo == true? my_foo = foo(idx);
Multidimension Handling
squeeze datagrid meshgrid remove singleton dimensions. A singleton dimension is any dim for which size(A,dim) = 1. data gridding & surface fitting. X and Y arrays for 3-D plots.
Differential Equations
ode23 ode45 solve DiffEqs, low order fit. solve DiffEqs, med order fit.
Signal Processing
conv xcorr filter fft pwelch tfe convolution and polynomial multiplication. auto- and cross-correlation 1-D digital filter. fast-fourier transform power spectral density transfer function estimate
Standard Math
sqrt abs log log10 round floor ceil rand randn square root. absolute value. natural logarithm. base-10 logarithm. round to nearest integer. round down. round up. uniform dist. random #s. Gaussian dist. random #s.
Handling Errors
warning error try catch end display warning message. display msg and abort function. exception handling. try a statement, if it returns an error, catch it and do another statement.
Statistics
sum sum of elements. nansum* sum ignoring NaNs. cumsum cumulative sum. mean average or mean value. std standard deviation. var variance. max largest component. min smallest component. range* diff between max & min. * requires Statistics Toolbox.
File I/O
ls, dir load save csvread csvwrite fopen fclose fread fwrite fprintf list directory contents. load workspace or text file from disk. save workspace or text file to disk. read comma sep. value file. write comma sep. value file. open file. close file. read binary data from file. write binary data to file. write formatted data to file.
Complex Math
real imag abs angle conj complex real part. complex imaginary part. complex modulus. phase angle. complex conjugate.
Algebra
roots poly find polynomial roots. convert roots to polynomial.
Trigonometric Functions
sin cos asin acos tan atan atan2
Symbolic*
syms* construct symbolic objects. subs* symbolic substitution. simplify* symbolic simplification. pretty* prettily print a symbolic expression. * requires Symbolic Math Toolbox.
Calculus
diff sum int gradient divergence curl numeric/symbolic derivative. numeric integration. symbolic integration. numerical gradient. divergence of vector field. curl of vector field.
Images
imread imwrite imshow imformats imadd* imsubtract* immultiply* imdivide* regionprops* read image from file. write image to file. display image from file. file format registry. math functions between two images.
CODE: x = -pi : pi/32 : pi; y = sin(x); figure(1); plot(x,y,'b.-'); axis([-pi pi -1 1]); title('title','FontSize', 12); xlabel('xlabel'); ylabel('ylabel'); legend('legend'); POINT STYLES: . point o circle x xs + plus * star s square d diamond v triangle (down) ^ triangle (up) > triangle (right) < triangle (left) LINE STYLES: - solid lines : dotted lines -. dash-dot lines -- dashed lines
Animation
aviinfo avifile addframe aviread information about AVI file. create a new AVI file. add a frame to AVI object. read/open AVI file.
Common Errors
inner matrix dimensions must agree You tried to multiply two matrices. Did you want to multiply them element-by-element? index exceeds matrix dimensions You tried to access an element of an array with an index value that was greater than the size of the array. All matrices on a row in the bracketed expression must have the same number of rows. You tried to concatenate two matrices of dissimilar size. Maybe transpose one? In an assignment A(:,matrix) = B, the number of rows in A and B must be the same. Check the sizes of both A and B. Chances are you are trying to set a row or column equal to an element (single value), or an element (single value) to a row or column.