You are on page 1of 2

Matlab Cheat Sheet Built in functions/constants Tables

abs(x) absolute value T=table(var1,var2,...,varN) Makes table*


pi 3.1415... T(rows,vars) get sub-table
Some nifty commands inf T{rows,vars} get data from table
clc Clear command window eps floating point accuracy T.var or T.(varindex) all rows of var
clear Clear system memory 1e6 106 T.var(rows) get values of var from rows
clear x Clear x from memory sum(x) sums elements in x summary(T) summary of table
commandwindow open/select commandwindow cumsum(x) Cummulative sum T.var3(T.var3>5)=5 changes some values
whos lists data structures prod Product of array elements T.Properties.Varnames Variable names
whos x size, bytes, class and attributes of x cumprod(x) cummulative product T = array2table(A) ! make table from array
ans Last result diff Difference of elements T = innerjoin(T1,T2) innerjoin
close all closes all figures round/ceil/fix/floor Standard functions.. T = outerjoin(T1,T2) outerjoin !
close(H) closes figure H *Standard functions: sqrt, log, exp, max, min, Bessel Rows and vars indicate rows and variables.
winopen(pwd) Open current folder *Factorial(x) is only precise for x < 21 tables are great for large datasets, because they
class(obj) returns objects class use less memory and allow faster operations.
save filename saves all variables to .mat file *rowfun is great for tables, much faster than eg. looping
save filename x,y saves x,y variables to .mat file Cell commands A cell can contain any variable type.
save -append filename x appends x to .mat file x=cell(a,b) a b cell array matrix and vector operations/functions
load filename loads all variables from .mat file x{n,m} access cell n,m x=[1, 2, 3] 1x3 (Row) vector
cellfun
ver Lists version and toolboxes cell2mat(x) transforms cell to matrix x=[1; 2; 3] 3x1 (Column) vector
beep Makes the beep sound cellfun(fname,C) Applies fname to cells in C x=[1, 2; 3, 4] 2x2 matrix
doc function Help/documentation for function x(2)=4 change index value nr 2
docsearch string search documentation x(:) All elements of x (same as x)
web google.com opens webadress Strings and regular expressions x(j:end) jth to last element of x
inputdlg Input dialog box strcomp compare strings (case sensitive) x(2:5) 2nd to 5th element of x
methods(A) list class methods for A strcompi compare strings (not case sensitive) x(j,:) all j row elements
strncomp as strcomp, but only n first letters x(:,j) all j column elements
strfind find string within a string diag(x) diagonal elements of x
, gives start position x.*y Element by element multiplication
Statistical commands Search for regular expression
distrnd random numbers from dist regexp x./y Element by element division
distpdf pdf from dist x+y Element by element addition
distcdf cdf dist x-y Element by element subtraction
distrnd random numbers from dist Logical operators A^n normal/Matrix power of A
hist(x) histogram of x && Short-Circuit AND. A.^n Elementwise power of A
histfit(x) histogram and & AND A Transpose
*Standard distributions (dist): norm, t, f, gam, chi2, bino || Short-Circuit or inv(A) Inverse of matrix
*Standard functions: mean,median,var,cov(x,y),corr(x,y), | or size(x) Rows and Columns
*quantile(x,p) is not textbook version. ~ not eye(n) Identity matrix
(It uses interpolation for missing quantiles. == Equality comparison sort(A) sorts vector from smallest to largest
~= not equal eig(A) Eigenvalues and eigenvectors
isa(obj, class_name) is object in class numel(A) number of array elements
*Other logical operators: <,>,>=,<= x(x>5)=0 change elemnts >5 to 0
Keyboard shortcuts *All above operators are elementwise x(x>5) list elements >5
edit filename Opens filename in editor *Class indicators: isnan, isequal, ischar, isinf, isvector find(A>5) Indices of elements >5
Alt Displays hotkeys , isempty, isscalar, iscolumn find(isnan(A)) Indices of NaN elements
F1 Help/documentation for highlighted function *Short circuits only evaluate second criteria if [A,B] concatenates horizontally
F5 Run code first criteria is passed, it is therefore faster. [A;B] concatenates vertically
F9 Run highlighted code And useful fpr avoiding errors occuring in second criteria For functions on matrices, see bsxfun,arrayfun or repmat
F10 Run code line *non-SC are bugged and short circuit anyway *if arrayfun/bsxfun is passed a gpuArray, it runs on GPU.
F11 Run code line, enter functions *Standard operations: rank,rref,kron,chol
Shift+F5 Leave debugger *Inverse of matrix inv(A) should almost never be used, use RREF
F12 Insert break point Variable generation through \ instead: inv(A)b = A\b.
Ctrl+Page up/down Moves between tabs j:k row vector [j,j+1,...,k]
Ctrl+shift Moves between components j:i:k row vector [j,j+i,...,k],
Ctrl+C Interrupts code linspace(a,b,n) n points linearly spaced
Ctrl+D Open highlighted codes file and including a and b
Ctrl+ R/T Comment/uncomment line NaN(a,b) ab matrix of NaN values
Ctrl+N New script ones(a,b) ab matrix of 1 values
Ctrl+W Close script zeros(a,b) ab matrix of 0 values
Ctrl+shift+d Docks window meshgrid(x,y) 2d grid of x and y vectors
Ctrl+shift+u Undocks window [a,b]=deal(NaN(5,5)) declares a and b
Ctrl+shift+m max window/restore size global x gives x global scope
Plotting commands Nonlinear nummerical methods if(criteria 1) if criteria 1 is true do procedure 1
fig1 = plot(x,y) quad(fun,a,b)
2d line plot, handle set to fig1 simpson integration of @fun procedure1
set(fig1, LineWidth, 2) change line width from a to b elseif(criteria 2) ,else if criteria 2 is true do procedure 2
set(fig1, LineStyle, -) dot markers (see *) fminsearch(fun,x0) minimum of unconstrained procedure2
set(fig1, Marker, .) marker type (see *) multivariable function else , else do procedure 3
set(fig1, color, red) line color (see *) using derivative-free method procedure3
set(fig1, MarkerSize, 10) marker size (see *) fmincon minimum of constrained function end
set(fig1, FontSize, 14) fonts to size 14 Example: Constrained log-likelihood maximization, note the -
figure new figure window Parms_est = fmincon(@(Parms) -flogL(Parms,x1,x2,x3,y) switch switch_expression if case n holds,
figure(j) graphics object j ,InitialGuess,[],[],[],[],LwrBound,UprBound,[]); case 1 run procedure n. If none holds
get(j) returns information procedure 1 run procedure 3
graphics object j case 2 (if specified)
gcf(j) get current figure handle
Debbuging etc. procedure 2
keyboard Pauses exceution otherwise
subplot(a,b,c) Used for multiple
return resumes exceution procedure 3
figures in single plot
tic starts timer end
xlabel(\mu line,FontSize,14) names x/y/z axis
toc stops timer
ylim([a b]) Sets y/x axis limits
profile on starts profiler
for plot to a-b General comments
profile viewer Lets you see profiler output
title(name,fontsize,22) names plot
try/catch Great for finding where Monte-Carlo: If sample sizes are increasing generate largest
grid on/off; Adds grid to plot
errors occur size first in a vector and use increasingly larger portions for
legend(x,y,Location,Best) adds legends
dbstop if error stops at first calculations. Saves time+memory.
hold on retains current figure
error inside try/catch block
when adding new stuff Trick: Program that (1) takes a long time to run and (2)
dbclear clears breakpoints
hold off restores to default doesnt use all of the CPU/memory ? - split it into more
dbcont resume execution
(no hold on) programs and run using different workers (instances).
lasterr Last error message
set(h,WindowStyle,Docked); Docked window
lastwarn Last warning message Matlab is a column vector based language, load memory
style for plots
break Terminates executiion of for/while loop columnwise first always. For faster code also prealocate
datetick(x,yy) time series axis
waitbar Waiting bar memory for variables, Matlab requires contiguous memory
plotyy(x1,y1,x2,y2) plot on two y axis
refreshdata refresh data in graph usage!. Matlab uses copy-on-write, so passing pointers
if specified source (adresses) to a function will not speed it up. Change
Data import/export variable class to potentially save memory (Ram) using:
drawnow do all in event queue
* Some markers: , +, *, x, o, square xlsread/xlswrite Spreadsheets (.xls,.xlsm) int8, int16, int32, int64, double, char, logical, single
* Some colors: red, blue, green, yellow, black readtable/writetable Spreadsheets (.xls,.xlsm)
dlmread/dlmwrite text files (txt,csv) You can turn the standard (mostly) Just-In-Time
* color shortcuts: r, b, g, y, k compilation off using: feature accel off. You can use
* Some line styles: -, --, :, -. load/save -ascii text files (txt,csv)
load/save matlab files (.m) compiled (c,c++,fortran) functions using MEX functions.
* shortcut combination example: plot(x,y,b--o)
imread/imwrite Image files
Avoid global variables, they user-error prone and compilers
Output commands cant optimize them well.
format short Displays 4 digits after 0 Programming commands Functions defined in a .m file is only available there.
format long Displays 15 digits after 0 return Return to invoking function Preface function names with initials to avoid clashes, eg.
disp(x) Displays the string x exist(x) checks if x exists MrP function1.
disp(x) Displays the string x G=gpuArray(x) Convert varibles to GPU array
num2str(x) Converts the number in x to string function [y1,...,yN] = myfun(x1,...,xM) Graphic cards(GPU)s have many (small) cores. If (1)
num2str([nA is = OFTEN USED! Anonymous functions not stored in main programme program is computationally intensive (not spending much
num2str(a)]) ! myfun = @(x1,x2) x1+x2; time transfering data) and (2) massively parallel, so
mat2str(x) Converts the matrix in x to string or even using computations can be independent. Consider using the GPU!
int2str(x) Converts the integer in x to string myfun2 = @myfun(x) myfun(x3,2) Using multiple cores (parallel computing) is often easy to
sprintf(x) formated data to a string
implement, just use parfor instead of for loops.

System commands Conditionals and loops Warnings: empty matrices are NOT overwritten ([] + 1 = []).
addpath(string) adds path to workspace for i=1:n Rows/columns are added without warning if you write in a
genpath(string) gets strings for subfolders procedure Iterates over procedure nonexistent row/column. Good practise: Use 3i rather than
pwd Current directory end incrementing i from 1 to n by 1 3*i for imaginary number calculations, because i might have
mkdir Makes new directory been overwritten by earlier. 1/0 returns inf, not NaN. Dont
tempdir Temporary directory use == for comparing doubles, they are floating point
inmem Functions in memory while(criteria) precision for example: 0.01 == (1 0.99) = 0.
exit Close matlab procedure Iterates over procedure
dir list folder content end as long as criteria is true(1) Copyright c 2015 Thor Nielsen (thorpn86@gmail.com)
ver lists toolboxes http://www.econ.ku.dk/pajhede/

You might also like