Sie sind auf Seite 1von 2

Matlab Cheat Sheet Built in functions/constants Standard Matrix and vector operations

abs(x) absolute value x=[1, 2, 3] 1x3 (Row) vector defined


pi 3.1415... x=[1; 2; 3] 3x1 (Column) vector defined
Some nifty commands inf ∞ x=[1, 2; 3, 4] 2x2 matrix
clc Clear command window eps floating point accuracy x(2)=4 change index value nr 2
clear Clear system memory 1e6 106 x.*y Element by element multiplication
clear x Clear x from memory sum(x) sums elements in x x./y Element by element division
ans Last result cumsum(x) Cummulative sum x+y Element by element addition
close all closes all figures prod Product of array elements x-y Element by element subtraction
close(H) closes figure H cumprod(x) cummulative product A^n normal/Matrix power of A
whos lists data structures diff Difference of elements A.^n Elementwise power of A
winopen(pwd) Open current folder round/ceil/fix/floor Standard functions.. A’ Transpose
class(obj) returns objects class *Standard functions: sqrt, log, exp, max, min, Bessel inv(A) Inverse of matrix
int16(x)=y convert doubles to Integers *Factorial(x) is only precise for x < 21 size(x) Rows and Columns
dlmread(’path’) Reads data eye(n) Identity matrix
dlmwrite(’path’,M) Writes M to path sort(A) sorts vector from smallest to largest
save filename saves all variables to .mat file
Cell commands A cell can contain any variable type. eig(A) Eigenvalues and eigenvectors
x=cell(a,b) a ×b cell array *Standard operations: rank,rref,kron,chol
save filename x,y saves x,y variables to .mat file
x{n,m} access cell n,m *Inverse of matrix inv(A) should almost never be used, use RREF
save -append filename x appends x to .mat file cellfun
cell2mat(x) transforms cell to matrix through \ instead: inv(A)b = A\b.
load filename loads all variables from .mat file
cellfun(’fname’,C) Applies fname to cells in C
ver Lists version and toolboxes
beep Makes the beep sound Matrix and vector operations/functions
doc function Help/documentation for function x(x>5)=0 change elemnts >5 to 0
docsearch string search documentation
Strings and regular expressions x(x>5) list elements >5
strcomp compare strings (case sensitive) find(A>5) Indices of elements >5
web google.com opens webadress
strcompi compare strings (not case sensitive) find(isnan(A)) Indices of NaN elements
inputdlg Input dialog box
strncomp as strcomp, but only n first letters B=repmat(A,m,n) Makes B from A
strfind find string within a string bsxfun(fun,A,B) Binary operation on two arrays
, gives start position arrayfun(fun,A1,...,An) Calls function m times, gets n inputs
regexp Search for regular expression m times from arrays
Portions of matrices and vectors
x(:) All elements of x *if arrayfun/bsxfun is passed a gpuArray, it runs on GPU.
x(j:end) j’th to end element of x
x(2:5) 2nd to 5th element of x Logical operators Statistical commands
x(j,:) all j row elements && Short-Circuit AND. hist(x) histogram
x(:,j) all j column elements & AND distrnd random numbers from dist
diag(x) diagonal elements of x || Short-Circuit or distpdf pdf from dist
[A,B] concatenates horizontally | or distcdf cdf dist
[A;B] concatenates vertically ~ not distrnd random numbers from dist
== Equality comparison distpdf pdf from dist
~= not equal distcdf cdf dist
isa(obj, ’class_name’) is object in class *Standard distributions (dist): norm, t, f, gam, chi2, bino
*Other logical operators: <,>,>=,<= *Standard functions: mean,median,var,cov(x,y),corr(x,y),
Keyboard shortcuts *All above operators are elementwise *quantile(x,p) is not textbook version.
edit filename Opens filename in editor *Class indicators: isnan, isequal, ischar, isinf, isvector (It uses interpolation for missing quantiles.
Alt Displays hotkeys , isempty, isscalar, iscolumn *Like most programs, histogram is not a true histogram.
F1 Help/documentation for highlighted function *Short circuits (SC) only evaluate second criteria if
F5 Run code first criteria is passed, it is therefore faster.
F9 Run highlighted code Structures
And useful fpr avoiding errors occuring in second criteria StructName.FieldName = Makes structure,
F10 Run code line *non-SC are bugged and short circuit anyway and variable named fieldname.
F11 Run code line, enter functions Sets value to struct, cell
Shift+F5 Leave debugger vector or a structure.
F12 Insert break point Variable generation StructName(2).FieldName Second element of structure
Ctrl+Page up/down Moves between tabs j:k row vector [j,j+1,...,k] getfield(StructName,’FieldName’) Gets data from
Ctrl+shift Moves between components j:i:k row vector [j,j+i,...,k], structure with fieldname
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) a×b matrix of NaN values
Ctrl+N New script ones(a,b) a×b matrix of 1 values
Ctrl+W Close script zeros(a,b) a×b 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
plot(x,y,’Linewidth’,2) plots x,y points quad(fun,a,b) simpson integration of @fun procedure1
grid adds gridlines from a to b elseif(criteria 2) ,else if criteria 2 is true do procedure 2
set(gca, ’FontSize’, 14) all fonts to size 14 fminsearch(fun,x0) minimum of unconstrained procedure2
mesh(x,y,z) plots x,y,z points multivariable function else , else do procedure 3
figure new figure window using derivative-free method procedure3
figure(j) graphics object j fmincon minimum of constrained function end
get(j) returns information Example: Constrained log-likelihood maximization, note the -
graphics object j Parms_est = fmincon(@(Parms) -flogL(Parms,x1,x2,x3,y) switch switch_expression if case n holds,
subplot(a,b,c) Used for multiple ,InitialGuess,[],[],[],[],LwrBound,UprBound,[]); case 1 run procedure n. If none holds
figures in single plot procedure 1 run procedure 3
xlabel(’\mu line’,’FontSize’,14) names x/y/z axis Debbuging etc. case 2 (if specified)
ylim([a b]) Sets y/x axis limits keyboard Pauses exceution procedure 2
for plot to a-b return resumes exceution otherwise
title(’name’,’fontsize’,22) names plot tic starts timer procedure 3
grid on; Adds grid to plot toc stops timer end
legend(’x’,’y’,’Location’,’Best’) adds legends profile on starts profiler
hold on retains current figure profile viewer Lets you see profiler output General comments
when adding new stuff try/catch Great for finding where • Monte-Carlo: If sample sizes are increasing generate longest
hold off restores to default errors occur size first in a vector and use increasingly larger portions for
(no hold on) dbstop if error stops at first calculations.
set(h,’WindowStyle’,’Docked’); Docked window error inside try/catch block
style for plots dbclear clears breakpoints • Trick: Program that (1) takes a long time to run and (2)
fill usefull for dbcont resume execution doesnt use all of the CPU/memory ? - split it into more
coloring polygons lasterr Last error message programs and run using different workers (instances).
datetick(’x’,yy) time series axis lastwarn Last warning message • Matlab is a column vector based language, load memory
semilogx(x,y) plot x on log scale break Terminates executiion of for/while loop columnwise first always.
semilogy(x,y) plot y on log scale waitbar Waiting bar
• Matlab uses copy-on-write, so passing pointers (adresses) to
loglog(x,y) plot y,x on log scale
a function will not speed it up.
For printing figure h to .eps files use: Data import/export
xlsread/xlswrite Spreadsheets (.xls,.xlsm) • You can turn the standard (mostly) Just-In-Time
print(figure(h),’-depsc2’,’path\image.eps’)
readtable/writetable Spreadsheets (.xls,.xlsm) compilation off using: feature accel off. You can use
dlmread/dlmwrite text files (txt,csv) compiled (c,c++,fortran) functions using MEX functions.
load/save -ascii text files (txt,csv) • For faster code also prealocate memory for variables,
Output commands load/save matlab files (.m) Matlab requires contiguous memory usage!.
format short Displays 4 digits after 0 imread/imwrite Image files
format long Displays 15 digits after 0 • Some excellent toolboxes: MFE toolbox (Econometrics).
disp(x) Displays the string x • Functions defined in a .m file is only available there, give
Programming commands
disp(x) Displays the string x own file if they are used otherplaces and name them as
return Return to invoking function
num2str(x) Converts the number in x to string myfun.m if called myfun in definition.
exist(x) checks if x exists
num2str([’nA is = ’ OFTEN USED!
G=gpuArray(x) Convert varibles to GPU array • Graphic cards(GPU)’s have many (small) cores. If (1)
num2str(a)]) !
function [y1,...,yN] = myfun(x1,...,xM) program is computationally intensive (not spending much
mat2str(x) Converts the matrix in x to string
Anonymous functions not stored in main programme time transfering data) and (2) massively parallel, so
int2str(x) Converts the integer in x to string
myfun = @(x1,x2) x1+x2; computations can be independent. Consider using the GPU!
sprintf(x) formated data to a string
or even using
myfun2 = @myfun(x) myfun(x3,2) • Using multiple cores (parallel computing) is often easy to
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)
ver lists toolboxes

Das könnte Ihnen auch gefallen