Title: Matlab Programming Tips and Tricks
1Matlab Programming Tips and Tricks
- Samuel Cheng
- University of Oklahoma-Tulsa
2Myth
- Matlab is slow
- Think again!
- Matlab is extremely fast for matrix computation
- Matlab is an encapsulation of highly optimized
Lapack and Blas numerical library
3Experiment 1
- Matrix multiplication for matrices of size 500 ?
500 - C 4.08 sec
- Matlab 0.53 sec
size500 for (i0iltsizei) for
(j0jltsizej) for (k0kltsizek)
cijaikbkj
Dont expect your tiny C code will beat Matlab
for matrix operations! Matlab is slow only when
you make it so!
4Flow Control
- Matlab is a fully power programming language with
flow control capability of other high level
languages - If-then-else
- for-end
- while-end
- try-catch-end
In most cases, you dont need them at all if you
do things right!
5Matlab
- Matlab is not Math lab
- It is Matrix lab
- Think everything in matrix
6Vectors and Matrices
- Row vectors
- Column vectors and transpose
- Matrices
gtgt X1,3,5,7,9
gtgt X13579 gtgt X1,3,5,7,9
gtgt Xzeros(2) X0,00,0 gtgt Xones(2)
X1,11,1 gtgt Xeye(2) X1,00,1
7Colon
gtgt X15 X1 2 3 4 5
Comment sign
gtgt X00.31 X0 0.3 0.6 0.9
gtgt Xones(2) gtgt X() ans 1 1 1 1
8Colon
gtgt X15 X1 2 3 4 5
Comment sign
gtgt X00.31 X0 0.3 0.6 0.9
gtgt Xones(2) gtgt X() ans 1 1 1 1
9Dot Products
- Every operation in Matlab is matrix operation by
default - Non-matrix operation is generalized to matrix
operation as element-wise operation (sin, cos,
etc.) - To convert matrix operation to element-wise
operation, add dot in front (.,.)
gtgt Aones(2) A.2 ans 1 1 1 1
gtgt Aones(2) A2 ans 2 2 2 2
10Most Important Tip
- Avoid loops by all means
- E.g. ysin(x), x0.1,0.2,,2pi
- Stupid code
- Better
for i12pi10
x0.1i y(i)sin(x) end
x0.10.12pi ysin(x)
11ndgrid
gtgt xid1yid1 gtgt for x-100.110 for
y-100.110 z(xid,yid)x3y2 yidyid1
end xidxid1 end
gtgt x,yndgrid(-100.110, -100.110) zx.3
y.2
12Batch File
- Batch file in Matlab is simple. Simply put your
code in a file with extension .m - Every symbols will be visible in the current
workspace - Good for initial development
13function
- Functions are exactly the same as batch files
except they hide all variables except those you
return
- Dont assume dimensions of your inputs (dont
assume your input to be a column or row vector) - Break your function into meaningful functions (a
well-design program needs very few comments) - Use functions whenever possible (instead of batch)
14function
gtgt type isprime1.m function boolisprime1(n) bool
1 for i2floor(sqrt(n)) if mod(n,i)0 bool
0 break end end gtgt boolisprime1(n) gtgt i ???
Undefined function or variable i.
- Exercise can you write the function above in 1
line?
15Answer
gtgt type isprime2.m function boolisprime2(n) bool
all(mod(nones(floor(sqrt(n))-1,1)',
2floor(sqrt(n))))
16function pointer
gtgt add_at_(x,y) xy add _at_(x,y)xy gtgt
add(1,2) ans 3 gtgt addone_at_(x) add(1,x) gtgt
addone(3) ans 4
17size / length
gtgt Xones(4,5) gtgt size(X) ans 4 5 gtgt
size(X,2) ans 5 gtgt size(X()) ans 20 1 gtgt
length(X()) ans 20
18size / length
gtgt type better.m Ximread(mypic.png) nXsize(X
,1) nYsize(X,2) process(X,nX,nY)
gtgt type horrible.m Ximread(mypic.png) nX320
nY200 process(X,nX,nY)
gtgt type best.m Ximread(mypic.png) process_new
(X)
Dont put fixed values all over your codes! Ill
never change their values is not an excuse
19find
- E.g. thresholding
- Bad
- Better
function xthreshold(x,th) for
xid1length(x) if abs(x(xid))ltth x(xid)0 en
d
function xthreshold(x,th) indfind(abs(x)ltth)
x(ind)0
x(abs(x)ltth)0
20exist
gtgt type threshold.m function xthreshold(x,th) if
exist(th,var) th1 end x(abs(x)ltth)0
Use exist to assign default variables for your
functions
21sprintf and eval
gtgt type bad.m Process(b1) Process(b2) Process(b
3) Process(b4) Process(b5)
General rule Write codes with low entropy
(deterministic)
gtgt type good.m for id15 eval(sprintf(Process(
bd),id)) end
22cell
- Cell arrays/matrices can store mixed content for
each component
gtgt a1,12,a a 1 1x2 double a gtgt
a(2) ans 1x2 double gtgt a2 ans 1 2
23File I/O
- fopen
- fread
- fwrite
- fprintf
- save/load
More or less same as C
gtgt save tmp a b c gtgt load tmp gtgt save tmp2 a
-ascii
24Debugging
- Use dbstop to initiate debugger
- Use dbclear all to erase all stop points
- Shortcuts
- F10 step over
- F11 step in
- Shift-F11 run to next stop point
- F12 toggle stop point
25try/catch
gtgt xrand(1,99) gtgt for i1100
y(i)x(i)2 end ??? Index exceeds matrix
dimensions.
gtgt for i1100 try y(i)x(i)2 catch i
end end i 100
26Visualization Functions
- ezplot
- plot
- plot3
- mesh
- surf
-
- See help document
27Most Common FAQs for Figures
gtgt axis off
gtgt axis(xstart xend ystart yend)
Click axis gtgt set(gca,fontsize,fontsize)
gtgt title(\fracxy,interpreter,latex)
28GUI
29Interface with C
- Matlab can be slow with non-matrix operation
- Look for internal function in those cases
- Speed up by interfacing with C
30Profiling
- Using tic/toc
- Matlab has its own profiling tools
- help profile
gtgt Arand(500) gtgt tic AA toc Elapsed time
is 0.329000 seconds.
31Interface with OS
- Write out file
- Call command line excutable
- Read file
gtgt type interface.m function Imoutinterface(size
,parameter) Imgenerate_img(size) imwrite(Im,tmp
.png) system(sprintf(process tmp.png
d,parameter)) Imoutimread(tmp.png)
32Interface with Java
gtgt type SC.java public class SC public double
add(double a,double b) return ab
Compile source and create JAR file
gtgt !javac SC.java gtgt !jar cvf skeleton.jar
SC.class added manifest adding SC.class(in
250) (out 194)(deflated 22)
33Interface with Java
Import class
gtgt javaaddpath ./skeleton.jar gtgt import SC
Create and use object
gtgt a SC a Skeleton_at_32b427c1 gtgt
a.add(1,2) ans 3
34Interface with Java
- Always remember to set functions/members to
public if you intent to access them through
Matlab - You would like to clear and re-import (and also
remove and re-add path) jar file if you make
changes to your java source - If you do not use default package (for example,
use package p), you should perform import p.SC
instead of import SC
35Interface with C using Mex
gtgt type mex_skeleton.c include "mex.h" void
mexFunction(int nlhs, mxArray plhs, int nrhs,
const mxArray prhs) double y,x1,x2 int
nrows,ncols nrows mxGetM(prhs0) ncols
mxGetN(prhs0) plhs0
mxCreateDoubleMatrix(nrows,ncols,mxREAL) x1
mxGetPr(prhs0) x2 mxGetPr(prhs1) y
mxGetPr(plhs0) process(x1,x2,y)
36Interface with C using Mex
gtgt mex mex_skeleton.c gtgt x1rand(1,10) gtgt
x2rand(1,10) gtgt y mex_skeleton(x1,x2)
37Conclusions
- Matlab can be fast in terms of both development
and actual running, an extremely good tool for
prototyping - Avoid loop in all means
- Getting help
- Use help often
- Google matlab command
- Email me or knock my door (try afternoon and
evening)