Sunteți pe pagina 1din 4

Matlab cheat sheet Basics

Brian McGill Feb 2000

expression<enter> and expression, expression <enter> prints result while expression;<enter> does not var=expression stores it (variable names are case sensitive) continues a line % comment continues to end of line expressions use: + - * / ^ () .* ./ ^ mod log log10 log2 exp sqrt pi eps realmin realmax flops logical expressions: < <= > >= == ~= & | ~ xor(x,y) any(x) all(x) rounding: fix (towards 0) floor ceil round (nearest int) imaginary numbers: 1+2i abs() angle() real() imag() whos [-file file] shows existing variables while clear varname removes and save filebase [var1, ] [-append] saves to filebase.mat and load filebase [var1 ] brings it back clc clears the screen and format short/long/short e/long e/short g/long g/hex/+/bank formats output dir which('func') exists('name'[,'type'])

Arrays
[a b c] gives a row vector [a; b; c] gives a column vector [a b c; d e f] gives a 2X3 array indexing: a[idx1, idx2, ] subscripts where idxn can be n or [n1 n2 n3] or : or end or n1:n2 or n1:step:n2 (note step can be negative) also a[:] column vectorizes and a[i] gets ith entry creating: (start:end) or (start:end:step) or linspace(start,end,#) or logspace(start,end,#) or zeros(n1,) or ones(n1, ) or eye(n)(identity) or rand(n) or rand(n1,n2,) or randn(n)(normal) or repmat(val,n1,) searching: find(A rel val) returns i indices, [r,c]=find() returns r,c A(find(A rel)) returns entries meeting criteria just find(A) returns non-zero elements functions: (transpose) . (complex conj) diag(vec) diag(ary) size(A) size(A,n) dot(v1,v2) updating: a subscripted array may be on LHS of =; a scalar is expanded; setting to [ ] deletes a row or column i=find(isnnan(A)); a(i)=zeros(size(i)); set type functions: unique(A)ismember(a,b) union(a,b) intersect(a,b) setxor(a,b) setdiff(a,b) check: isempty isnumeric islogical isnan isinf isfinite isequal(x,round(x)) isreal

Functions
funcname.m function outvar=funcname(arg1,arg2,arg3) %help text % and more if nargin<3, arg3=default3; end if nargin<2, arg2=default2; end statement; outvar=2*3; outvar can be [outvar1, outvar2] nargout also useable no outvars behave syntactically like commands error(string) fails out fprintf(fmt,.) or command w/ no ';' for output [x,y]=feval(funcname,arg1,arg2,) GLOBAL var edit func (no .m needed)

Control structures
if expr, statement; statement; elseif statements else statements end while expression statement; end try statements catch statements end for var=rowvec statement; end e.g. for n=1:10 picks up columns break is usable in all switch expression case testexpr statement; case {ex1, ex2} statement; otherwise statement; end

Cells & Structures


Cell=array of subarrays to access subarray use arry{i,j} [=arry2] creation: { } conversion: string/cell: char/cellstr number/cell: {} or or [ary{:}] or cat(1,ary{:})/num2cell Struct=fields X records as cells struct(i).field fieldnames(struct) struct('f1',val1,'f2',val2,) conversion: struct2cell/cell2struct

Strings
this is a string help strfun strings are numerical arrays of ASCII values: e.g. size(how long) gives 1 8 and subscripting works char or str2mat gives a 2-D array w/ variable # of columns - char(str1, str2 is longer) access these by mystrlist(n,:) concatenation: ['str1' 'str2' 'str3'] or for multirow strings: strcat(a,b) concatenates strings as long as they have the same # of rows numeric conversion: int2str(n) num2str(f) and sprintf(fmt,num) ischar(S) isletter(S) isspace(S) lower(S) upper(S) sttrep(s1,s2,s3) findstr(S1,S2) strcmp(S1,S2) strncmp(S1,S2,n) strtok(S1,D) strmatch(s,sary) eval(str) str2num() num2str()

Basic analysis
func(array)all array or func(array,1) works across rows while mean(array,2) works across columns mean, max, min, cov, diff, std(a,[0/1[,dir]]), sum, prod, sort, rank, cumsum, cumprod [val, index]=max()/min() in std, 0 means n-1, 1 means n polyfit(x,y,n) interpl(x,y,val[,cubic,spline,nearest]) function functions: func can be m-file, string (w/ x), inline func (var=inline(str) ) optimization: fmin(func,min,max) fmin(ndfunc,initguessvec) zeros: fzero(func[,start=0]) integration: quad(f,a,b[,tol]) difeq: ode45(func,[beg end],init) where func is a .m file taking yprime=func(t,y) integration: trapz(x,y) quad(inlfunc,lo,hi) quad8 dblquad differentiation: diff(y)./diff(x) det(A) eig(A)[V,D]=eig(A)expm(A)inv(A)norm(A) norm(A,p)poly(A)rank(A)svd(A)trace(A) jordan(A), colspace(A)

Symbolic
1) expr or 2) syms a b then expr w/ a,b or 3) sym(num) or 4) symop(2,+,x) [n, d]=numden(se) compose(f1,f2) finverse(f) double(se) sym2poly(f) poly2sym(v) subs(se,var,var/num) symsum(f) symsum(f,a,b) diff(f) diff(f,var) diff(f,n) int(f,a,b) solve(se) solve(se,var) solve(se1,se2,,var1,var2, ) dsolve(difeq[,var]) where difeq uses Dy,y, Dny w/ (0) for init and has multiple expr sep by , det(matrixse) inv(matrixse) eig(matrixse) [V,D]=eig(matrixse) jordan, svd, colspace, null taylor(se) jacobian(se,var1,var2) laplace(func,var,newvar) fourier(f,fv,nv) ztrans(f,v,n) simplify(f) factor(f) expand(f) simple(f) vpa(se,digits) pretty(se) latex(se) ccode(se)

Graphing
plot([x,]y[,style],) where style is string of color/symbol/line bgrcmykw .ox+*sd^<>vph - : -. -grid on/off; xlabel(str) ylabel(str) title(str) legend(str1,str2,) glabel(X/Y/T,size[,color]) color: ymcrgbwk symbols: .ox+*sdv^<>ph line: -, :, -., -gbanner(haxis,string[,ptsz]); Tex labels: superscript: ^{} subscript: _{} \alpha axis([xmin xmax ymin ymax]) axis auto; axis manual (freezes); axis square; axis equal; hold on; hold off; subplot(rows,cols,graph); figure; loglog simlogx semilogy all as plot bar([x,]y[,width][,stacked]) pie(vec[,ispulledvec]) hist(vec[,binvec]) errorbar(x,y,e) plotmatrix(x,y) as scatter fplot(f,[xmin xmax]) fplot(f,[xmin xmax ymin max]) ezplot(f) 3D: xr=0:0.1:1; yr=0:0.1:1; [x y]=meshgrid(xr,yr); z=x+y.*z; then mesh(x,y,z) surf(x,y,z) countourf(x,y,z,n)=countour(x,y,z,n,style)+pcolor(x,y,z)

Help topics
help topic general ops lang elmat elfun control local glmlab lookfor verbage specfun matfun datafun polyfun funfun (&ODE) more on sparfun (sparse mat) graph2d graph3d specgraph graphics (handle) uitools strfun iofun timefun datatypes dde demos symbolic signal

Matlab Handle Graphics cheat sheet R o o t (c o m p u te r s c re e n ) F ig u r e # 1 F ig u r e U IC o n t r o l # 2 # 2 F ig u r e U IM e n u U IM e n u T e x t Im a g e S u rfa c e # 3

Brian McGill Feb 2000

U IC o n tr o l # 1

A x e s

# 1

A x e s

# 1

L in e L ig h t

P a tc h

Object Type Root Figure UIControl UIMenu Axes Text Line Patch Image Surface Light

Handles 0 gcf

Creators N/A figure uicontrol, btngroup uimenu, makemenu, winmenu, uicontextmenu axes, sbuplot(rows,cols,#) text(x,y[,z],string) line(vx,vy[,vz]) patch(vx,vy[,vz],color) image(bitmapmatrix) surface(x,y,z[,c]) light

Other utils clf, close, refresh btnstate, btnpress, btndown, btnup cla, box on/off, caxis, axis on/off, [xmin xmax ymin max] auto/manual/ij/xy/equal/square xlabel, ylabel, zlabel, title, gtext fill, fill3, rectangle imagesc

Comment Parent of all, holds defaults window (contains axes, controls, menus) Style main drawing areas xy places 0,0 in lower left ij places in upper left, y first text on an axis a set of lines a colored polygon a bitmap given by matrix adjacent polygons lighting of surfaces

gca, get(hFig, 'CurrentAxes'')

Property manipulation & inheritance


At any level there is a "shadow" property that gives defaults for all children given by prefixing 'Default' e.g. 'DefaultAxesFontSize' Hierarchy: inbuilt, root, figure, axes - at creation time all non-specified propeties taken from first Default found up hierarchy All the basic creator routines (axes, line, etc) all allow propname, propval, at tend of function calls set(h,propname,prop) get(h,propname) findobj([hvec,]propname1,propval1, ) clruprop/setuprop/getuprop allchild(h) reset(h) delete(h) copyobj(h)

Common properties objects


BusyAction, ButtonDownFcn,CreateFcn, ChangeFcn, DeleteFcn,Interruptible Children Selected UserData (any Matlab array) Clipping SelectionHighlight Visible ('on'/'off') HandleVisibility Tag (any string) Parent Type ('figure','axis','line', etc) Text properties: FontAngle (normal/italic/oblique); FontName; FontSize; FontUnits; FontWeight (light/normal/demi/bold); Extent* Units: (pixels/normalized (0-1)/inches/centimeters/points) Background Color: Color none/[r g b]/name except UIControl has BackgroundColor Drawing objects: EraseMode (normal/none/xor/background) Marker (.0+etc) MarkerEdgeColor MarkeFaceColor MarkerSize LineStyle LineWidth Location: XData/YData/ZData (line, patch, surface) Position (text, uicontrol) [L B W H] - Extent is readonly & gives minimum Axes (?=X/Y/Z): Title/Xlabel/Ylabel; ?Lim [min, max]; ?Dir normal/reverse; ?Grid on/off; ?LimMode auto/manual; ?Scale=linear/log; ?Tick vec; ?TickMode=auto/manual; ?TickLabel strings; ?TickLabelMode auto/manual; ?AxisLocation top/bottom/left/right; DataAspectRatio [dx dy dz]; DataAspectRatio Mode auto/manual; GridLineStyle -/--/:/-./none; LineWidth n; Clim [cmin, cmax]; CLimMode auto/manual; TickDir in/out; TickDirMode auto/manual; TickLength auto/manual; View [az, elev] Figure: CurrentAxes, CurrentCharacter*, CurrentObject, CurrentPoint, Name string, NumberTitle on/off; Pointer crosshair/arrow/watch etc; Resize off/on; WindowStyle normal/modal UIControl: style (pushbutton/radiobutton/checkbox/edit/text/slider/frame/listbox/popupmenu); Min n; Max n; Value n; String str; SliderStep [one page]

Array Indexing
3 modes:
1. 2. 3. a(commalist) a(idxlist) a(boollist) where each element in comma separated list matches 1 dimension in array where the array is treated as a column vector regardless of shape (dim1 varies fastest) where the array is treated as a column vector regardless of shape

commalist idxlist1,idxlist2,idxlist3 s.field where s is an array of structures cell{:} deal(ary)

or s(idxlist).field

reverse (commalist-> array) [commalist] or cat(dim,commalist) (array-> commalist) comamlist=deal(ary) assign [commalist]=deal(commalist) including [var1,var2,]=deal(commalist)

idxlist : type
n:m represents elements n thru m n:step:m represents incremental list end may be used for n or m : represents all elements

[ ] type
[n1 n2 n3 ]

n
a single #

boollist vector of 0/1's

nb: floats, x, converted to logicals by logical(x) while x>1

logicals

Tricks
idxlist=find(boolarray)
find converts a boolean list into a idxlist

idxlist ommissions, repetitions and reordering is respected add a row:


a(newrow,: )=0

remove a row
a(delrow,: )=[]

add a dimension
any dimension that is non-existent (or 1 position) can be subscripted with multiple 1's (e.g. [1 1 1 ]) e.g.: a=[1 2 3], a([1 1], : ) [1 2 3; 1 2 3]

concatenate arrays
[a1 a2] - horizontal (dim2) concatenation [a1; a2] vertical (dim1) concatenation

Stats
Distributions : beta* bino* chi2 exp* f gam* geo hyge logn nbin ncf nct ncx2 norm* poiss* rayl t unid unif* weib* Distr functions dist*fit distcdf distpdf distinv (of cdf) distrnd diststat (mean, var) Tools (nan)mean, median, min, max, std, sum prctile, range, skewness grpstats, crosstab, tabulate, bootstrp corrcoef, cov, simprank, simpcorr(x,y,printp) anova1, anova2, leverage, polyfit(x,y,n), polyval, , stepwise, regress(y,[1 x] nlinfit(x,y,inline(a(1)*x.^ a(2),a,x,ainit) cluster, pdist, linkage, princomp, barttest, classify (LDA) ranksum, signrank, signtest, ztest, ttest, ttest2, ks boxplot, gline, gname, normplot, refline, weibplot refcurve, refline([slp,[int]]), lllsline, llrefline disttool, polytool, regst

S-ar putea să vă placă și