Example: air traffic controller

Matlab Cheat Sheet Built in functions/constants Tables ...

Matlab Cheat SheetSome nifty commandsclcClear command windowclearClear system memoryclear xClear x from memorycommandwindowopen/select commandwindowwhoslists data structureswhos xsize, bytes, class and attributes of xansLast resultclose allcloses all figuresclose(H)closes figure Hwinopen(pwd)Open current folderclass(obj)returns objects classsave filenamesaves all variables to .mat filesave filename x,ysaves x,y variables to .mat filesave -append filename xappends x to .mat fileload filenameloads all variables from .mat fileverLists version and toolboxesbeepMakes the beep sounddoc functionHelp/documentation for functiondocsearch stringsearch documentationweb webadressinputdlgInput dialog boxmethods(A)list class methods for AStatistical commandsdistrndrandom numbers from distdistpdfpdf from distdistcdfcdf distdistrndrandom numbers from disthist(x)histogram of xhistfit(x)histogram and*Standard distributions (dist): norm, t, f, gam, chi2, bino*Standard functions: mean,median,var,cov(x,y),corr(x,y),*quan tile(x,p) isnottextbook version.

style for plots datetick(’x’,yy) time series axis plotyy(x1,y1,x2,y2) plot on two y axis ... Programming commands return Return to invoking function exist(x) checks if x exists ... Matlab is a column vector based language, load memory columnwise rst …

Tags:

  Programming, Styles, Matlab

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

Transcription of Matlab Cheat Sheet Built in functions/constants Tables ...

1 Matlab Cheat SheetSome nifty commandsclcClear command windowclearClear system memoryclear xClear x from memorycommandwindowopen/select commandwindowwhoslists data structureswhos xsize, bytes, class and attributes of xansLast resultclose allcloses all figuresclose(H)closes figure Hwinopen(pwd)Open current folderclass(obj)returns objects classsave filenamesaves all variables to .mat filesave filename x,ysaves x,y variables to .mat filesave -append filename xappends x to .mat fileload filenameloads all variables from .mat fileverLists version and toolboxesbeepMakes the beep sounddoc functionHelp/documentation for functiondocsearch stringsearch documentationweb webadressinputdlgInput dialog boxmethods(A)list class methods for AStatistical commandsdistrndrandom numbers from distdistpdfpdf from distdistcdfcdf distdistrndrandom numbers from disthist(x)histogram of xhistfit(x)histogram and*Standard distributions (dist): norm, t, f, gam, chi2, bino*Standard functions: mean,median,var,cov(x,y),corr(x,y),*quan tile(x,p) isnottextbook version.

2 (It uses interpolation for missing shortcutsedit filenameOpens filename in editorAltDisplays hotkeysF1 Help/documentation for highlightedfunctionF5 Run codeF9 Run highlightedcodeF10 Run code lineF11 Run code line, enter functionsShift+F5 Leave debuggerF12 Insert break pointCtrl+Page up/downMoves between tabsCtrl+shiftMoves between componentsCtrl+CInterrupts codeCtrl+DOpen highlightedcodes fileCtrl+ R/TComment/uncomment lineCtrl+NNew scriptCtrl+WClose scriptCtrl+shift+dDocks windowCtrl+shift+uUndocks windowCtrl+shift+mmax window/restore sizeBuilt in functions/constantsabs(x)absolute epsfloating point accuracy1e6106sum(x)sums elements in xcumsum(x)Cummulative sumprodProduct of array elementscumprod(x)cummulative productdiffDifference of elementsround/ceil/fix/floorStandard *Standard functions: sqrt, log, exp, max, min, Bessel*Factorial(x) is only precise forx <21 Cell commandsA cell can contain any variable (a,b)a b cell arrayx{n,m}access cell n,mcell2mat(x)transforms cell to matrixcellfun( fname ,C)Applies fname to cells in CcellfunStrings and regular expressionsstrcompcompare strings (case sensitive)strcompicompare strings (not case sensitive)strncompas strcomp, but only n first lettersstrfindfind string within a string, gives start positionregexpSearch for regular expressionLogical operators&&Short-Circuit ||Short-Circuit or|or~not==Equality comparison~=not equalisa(obj, class_name )is object in class*Other logical operators: <,>,>=,<=*Allaboveoperators areelementwise*Class indicators.)

3 Isnan, isequal, ischar, isinf, isvector, isempty, isscalar, iscolumn*Short circuits only evaluate second criteria iffirst criteria is passed, it is therefore useful fpr avoiding errors occuring in second criteria*non-SC are bugged and short circuit anywayVariable generationj:krow vector[j,j+1,..,k]j:i:krow vector[j,j+i,..,k],linspace(a,b,n)n points linearly spacedand including a and bNaN(a,b)a b matrix of NaN valuesones(a,b)a b matrix of 1 valueszeros(a,b)a b matrix of 0 valuesmeshgrid(x,y)2d grid of x and y vectors[a,b]=deal(NaN(5,5))declares a and bglobal xgives x global scopeTablesT=table(var1,var2,..,varN)Mak es table*T(rows,vars)get sub-tableT{rows,vars}get data from or T.(varindex)all rows of (rows)get values of var from rowssummary(T)summary of ( >5)=5changes some namesT = array2table(A)! make table from arrayT = innerjoin(T1,T2)innerjoinT = outerjoin(T1,T2)outerjoin !

4 Rows and vars indicate rows and are great for large datasets, because theyuse less memory and allow faster operations.*rowfun is great for Tables , much faster than eg. loopingmatrix and vector operations/functionsx=[1, 2, 3]1x3 (Row) vectorx=[1; 2; 3]3x1 (Column) vectorx=[1, 2; 3, 4]2x2 matrixx(2)=4change index value nr 2x(:)All elements of x (same as x)x(j:end)j th to last element of xx(2:5)2nd to 5th element of xx(j,:)all j row elementsx(:,j)all j column elementsdiag(x)diagonal elements of xx.*yElement by element by element divisionx+yElement by element additionx-yElement by element subtractionA^nnormal/Matrix power of AA.^nElementwise power of AA Transposeinv(A)Inverse of matrixsize(x)Rows and Columnseye(n)Identity matrixsort(A)sorts vector from smallest to largesteig(A)Eigenvalues and eigenvectorsnumel(A)number of array elementsx(x>5)=0change elemnts>5 to 0x(x>5)list elements>5find(A>5)Indices of elements>5find(isnan(A))Indices of NaN elements[A,B]concatenates horizontally[A;B]concatenates verticallyFor functions on matrices, see bsxfun,arrayfun or repmat*if arrayfun/bsxfun is passed a gpuArray, it runs on GPU.

5 *Standard operations: rank,rref,kron,chol*Inverse of matrix inv(A) should almost never be used, use RREF through\instead:inv(A)b=A\ commandsfig1 = plot(x,y)2d line plot, handle set to fig1set(fig1, LineWidth , 2)change line widthset(fig1, LineStyle , - )dot markers (see *)set(fig1, Marker , . )marker type (see *)set(fig1, color , red )line color (see *)set(fig1, MarkerSize , 10)marker size (see *)set(fig1, FontSize , 14)fonts to size 14figurenew figure windowfigure(j)graphics object jget(j)returns informationgraphics object jgcf(j)get current figure handlesubplot(a,b,c)Used for multiplefigures in single plotxlabel( \mu line , FontSize ,14)names x/y/z axisylim([a b])Sets y/x axis limitsfor plot to a-btitle( name , fontsize ,22)names plotgrid on/off;Adds grid to plotlegend( x , y , Location , Best )adds legendshold onretains current figurewhen adding new stuffhold offrestores to default(no hold on)set(h, WindowStyle , Docked ).

6 Docked windowstyle for plotsdatetick( x ,yy)time series axisplotyy(x1,y1,x2,y2)plot on two y axisrefreshdatarefresh data in graphif specified sourcedrawnowdo all in event queue* Some markers: , +, *, x, o, square* Some colors: red, blue, green, yellow, black* color shortcuts: r, b, g, y, k* Some line styles : -, --, :, -.* shortcut combination example: plot(x,y, b--o )Output commandsformat shortDisplays 4 digits after 0format longDisplays 15 digits after 0disp(x)Displays the string xdisp(x)Displays the string xnum2str(x)Converts the number in x to stringnum2str([ nA is = OFTEN USED!num2str(a)])!mat2str(x)Converts the matrix in x to stringint2str(x)Converts the integer in x to stringsprintf(x)formated data to a stringSystem commandsaddpath(string)adds path to workspacegenpath(string)gets strings for subfolderspwdCurrent directorymkdirMakes new directorytempdirTemporary directoryinmemFunctions in memoryexitClose matlabdirlist folder contentverlists toolboxesNonlinear nummerical methodsquad(fun,a,b)simpson integration of @funfrom a to bfminsearch(fun,x0)minimum of unconstrainedmultivariable functionusing derivative-free methodfminconminimum of constrained functionExample: Constrained log-likelihood maximization, note the -Parms_est = fmincon(@(Parms) -flogL(Parms,x1,x2,x3,y),InitialGuess,[] ,[],[],[],LwrBound,UprBound,[]).

7 Debbuging exceutionreturnresumes exceutionticstarts timertocstops timerprofile onstarts profilerprofile viewerLets you see profiler outputtry/catchGreat for finding whereerrors occurdbstop if errorstops at firsterror inside try/catch blockdbclearclears breakpointsdbcontresume executionlasterrLast error messagelastwarnLast warning messagebreakTerminates executiion of for/while loopwaitbarWaiting barData import/exportxlsread/xlswriteSpreadsheet s (.xls,.xlsm)readtable/writetableSpreadsh eets (.xls,.xlsm)dlmread/dlmwritetext files (txt,csv)load/save -asciitext files (txt,csv)load/savematlab files (.m)imread/imwriteImage filesProgramming commandsreturnReturn to invoking functionexist(x)checks if x existsG=gpuArray(x)Convert varibles to GPU arrayfunction [y1,..,yN] = myfun(x1,..,xM)Anonymous functions not stored in main programmemyfun = @(x1,x2) x1+x2;or even usingmyfun2 = @myfun(x) myfun(x3,2)Conditionals and loopsfor i=1:nprocedureIterates over procedureendincrementing i from 1 to n by 1while(criteria)procedureIterates over procedureendas long as criteria is true(1)if(criteria 1)if criteria 1 is true do procedure 1procedure1elseif(criteria 2),else if criteria 2 is true do procedure 2procedure2else, else do procedure 3procedure3endswitch switch_expressionif case n holds,case 1run procedure n.

8 If none holdsprocedure 1run procedure 3case 2(if specified)procedure 2otherwiseprocedure 3endGeneral comments Monte-Carlo:Ifsamplesizesareincreasing generate largestsize first in a vector anduseincreasinglylargerportions forcalculations. Saves time+memory. Trick: Program that (1) takes a long time to run and (2)doesnt use all of the CPU/memory ? - split it into moreprograms and run using different workers (instances). Matlab is acolumnvectorbased language, load memorycolumnwise first always. For faster code also prealocatememory for variables, Matlab requirescontiguousmemoryusage!. Matlab usescopy-on-write, so passing pointers(adresses) to a function will not speed it to potentially save memory (Ram) using:int8, int16, int32, int64, double, char, logical, single You can turn the standard (mostly)Just-In-Timecompilation off using: feature accel off.

9 You can usecompiled (c,c++,fortran) functionsusing MEX functions. Avoid global variables, they user-error prone and compilerscant optimize them well. Functions defined in a .m file is only available function names with initials to avoid clashes, Graphic cards(GPU) s have many (small) cores. If (1)program iscomputationallyintensive (not spending muchtime transfering data) and (2)massivelyparallel, socomputations can be independent. Consider using the GPU! Using multiple cores (parallelcomputing) is often easy toimplement, justuseparforinsteadofforloops. Warnings: empty matrices are NOT overwritten ([] + 1 = []).Rows/columns are added without warning if you write in anonexistent row/column. Good practise: Use 3i rather than3*i for imaginary number calculations, because i might havebeen overwritten by earlier. 1/0 returns inf, not NaN.

10 Dontuse == for comparing doubles, they are floating pointprecision for example: == (1 ) = 2015 Thor Nielsen


Related search queries