Example: stock market

MATLAB Fundamentals - Cheat Sheet - Tools Course ETH Zurich

MATLAB Fundamentals - Cheat Sheet - Tools Course ETH Z urichBasicsWorkspaceansMost recent answerclcclear command windowclearvarclear variables WorkspaceclfClear all plotsclose allClose all plotsctrl-cKill the current calculationdocfunopen documentationdisp( text )Print textformatshort longSet output display formathelpfunopen in-line helploadfilename{vars}load variables from .mat filesave{-append}file{vars}save var to fileaddpathpathinclude path to ..iskeywordargCheck if arg is keyword% This is a lines (with break)";" (after command)suppresses outputscriptnameruns , tocstart and stop timerverList of installed toolboxesMATLAB and Changing Variablesa = 5 Define variableato be 5A = [1, 2, 3, 4;SetAto be a 3 4 matrix5, 6, 7, 8; , separates columns9, 10, 11, 12] ; separates rows[A,B], horzcat(A,B)Concatenate arrays horizontally[A;B], vertcat(A,B)Concatenate arrays verticallyx(2) = 7 Change 2nd element ofxto 7A(2,1) = 0 ChangeA2,1to 0x(2:12)The 2nd to the 12th elem.

kron(A,B) Kronecker tensor product norm(x) Vector and matrix norms linsolve(A,B) Solve linear system of equations rank(A) Rank of matrix trace(A) Sum of diagonal elements curl(X,Y,Z,U,V,W) Curl and angular velocity divergence(X,..,W) Compute divergence of vector eld null(A) Null space of matrix orth(A) Orthonormal basis for matrix range

Tags:

  Nork

Information

Domain:

Source:

Link to this page:

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

Other abuse

Transcription of MATLAB Fundamentals - Cheat Sheet - Tools Course ETH Zurich

1 MATLAB Fundamentals - Cheat Sheet - Tools Course ETH Z urichBasicsWorkspaceansMost recent answerclcclear command windowclearvarclear variables WorkspaceclfClear all plotsclose allClose all plotsctrl-cKill the current calculationdocfunopen documentationdisp( text )Print textformatshort longSet output display formathelpfunopen in-line helploadfilename{vars}load variables from .mat filesave{-append}file{vars}save var to fileaddpathpathinclude path to ..iskeywordargCheck if arg is keyword% This is a lines (with break)";" (after command)suppresses outputscriptnameruns , tocstart and stop timerverList of installed toolboxesMATLAB and Changing Variablesa = 5 Define variableato be 5A = [1, 2, 3, 4;SetAto be a 3 4 matrix5, 6, 7, 8; , separates columns9, 10, 11, 12] ; separates rows[A,B], horzcat(A,B)Concatenate arrays horizontally[A;B], vertcat(A,B)Concatenate arrays verticallyx(2) = 7 Change 2nd element ofxto 7A(2,1) = 0 ChangeA2,1to 0x(2:12)The 2nd to the 12th elem.

2 Ofxx(1:3:end)Every 3rd elem. ofx(1st to last)x(x>6)List elements> (x>8)=8change elements using conditionA(4,:)Get the 4th row ofAA(:,3)Get the 3rd column ofAA(6, 1:3)Get 1st to 3rd elem in 6th rowzeros(9, 5)Make a 9 5 matrix of zerosones(9, 5)Make a 9 5 matrix of oneseye(7)Make a 7 7 identity matrixdiag(x)Create diagonal matrixdiag(A)Get diagonal elements of matrixmeshgrid(x)2-D and 3-D grids7:15 Row vector of 7,8,..,14,15a:ds:blin. spaced vector with spacing dslinspace(1,20,35)Lin. spaced vector (35 elements)logspace(1, 1e5, 50)Log. spaced vector (50 elements)Arithmetics+, -Addition, Subtraction (elementwise)A*BMatrix multiplicationA.*Belementwise divisionB.\ALeft array division/SolvexA=Bforx\SolveAx=BforxA nnormal/(square) matrix powerA. nElementwise power ofAsum(X)Sum of elements (along columns)prod(X)Product of elements (along columns)Elementary Functionssin(A)Sine of argument in radianssind(A)Sine of argument in degreesasin(A)Inverse sine in radianssinh(A)Hyperbolic sinethere are analogous elementwise trigonometric functionsforcos,tanandcotabs(A)Compute|x |sqrt(x)Compute xlog(x)Compute ln(x)log10(x)Compute log10(x)sign(x)sign ofxexp(x)exponential ofxComplex Numbersabs(z)Absolute value and complex magnitudeangle(z)Phase anglecomplex(a,b)Create complex numbersconj(z)Elementwise complex conjugatei or jImaginary unitimag(z)Imaginary part of complex numberisreal(z)Determine whether array is realreal(z)Real part of complex numberctranspose(Z)Complex conjugate transposeConstantspi = a number ( 0/0)

3 InfInfinityepsFloating-point relative accuracyrealmaxLargest positive floating-point numberrealminSmallest positive floating-point numberNumerics and Linear AlgebraNumerical Integration and Differentiationintegral(f,a,b)Numerical integrationintegral2(f,a,b,c,d)2D num. integrationintegral3(f,a,b,..,r,s)3D num. integrationtrapz(x,y)Trapezoidal integrationcumtrapz(x,y)Cumulative trapez integrationdiff(X)Differences (along columns)gradient(X)Numerical gradientMatrix Functions/ Linear AlgebraA Transpose of matrix or vectorinv(A)inverse ofA(use with care!)det(A)determinant ofAeig(A),eigs(A)eigenvalues ofA(subset)cross(A,B)Cross productdot(A,B)Dot productkron(A,B)Kronecker tensor productnorm(x)Vector and matrix normslinsolve(A,B)Solve linear system of equationsrank(A)Rank of matrixtrace(A)Sum of diagonal elementscurl(X,Y,Z,U,V,W)Curl and angular velocitydivergence(X,..,W)Compute divergence of vector fieldnull(A)Null space of matrixorth(A)Orthonormal basis for matrix rangemldivide(A,B)Solve linear systemAx=Bforxmrdivide(B,A)Solve linear systemxA=Bforxdecomposition(A)Matrix decompositionlsqminnorm(A,B)Least-square s solution to linear (A)Reduced row echelon formbalance(A)Diagonal scaling (improve eig.)

4 Vec.)svd(A)Singular value decompositiongsvd(A,B)Generalized svdchol(A)Cholesky factorizationMatrix manipulationcat(dim,A,B)Concatenate arraysndims(A)Number of array dimensionsflip(A)Flip order of elementsfliplr(A)Flip array left to rightflipud(A)Flip array up to downsqueeze(A)Remove dimensions of length 1reshape(A,sz)Reshape arraysize(A)size ofAsort(A)Sort array elementssortrows(A)Sort rows of matrix or tablelength(A)Length of largest array dimensionCheat Sheet for MATLAB Tools Course at ETH Z urich, by Res J ohrGraphicsPlottingplot(x,y) equalScale axes equallytitle( A Title )Add title to the plotxlabel( x axis )Add label to thexaxisylabel( y axis )Add label to theyaxislegend( foo , bar )Label 2 curves for the plotgridAdd a grid to the plothold on / offMultiple plots on single figurexlim /ylim / zlimget or set axes rangefigureStart a new plotPlot typesPlot gallery: methodsFunctions% defined in m-file% File must have the same name as the functionfunction output = addNumbers(x, y)output = x + y; %multiple or var nr of args possibleendAnonymous Functions% defined via function handlesf = @(x) cos(x.

5 2)./(3*x);Relational and logical operations==Check equality =Check inequality>greater than>=greater or equal to<less than<=less or equal to&,&&logical AND logical NOT|,||logical ORxorlogical exclusive-ORif, elseif Conditionsif n<10disp('n smaller 10')elseif n<20disp('n between 10 and 20')elsedisp('n larger than 20')end % control structures terminate with endSwitch Casen = input('Enter a number: ');switch ncase -1disp('negative one')case 0disp('zero')case{1,2,3}%check three cases togetherdisp('positive one')otherwisedisp('other value')end % control structures terminate with endFor-Loop%loop a specific number of times, and keep track of each ..iteration with an incrementing index variable%parfor might be used to parallelize the executionfor i = 1:3disp('cool'); % comment with some LATEXin it: x2end % control structures terminate with endWhile-Loop%loops as long as a condition remains truen = 1;nFactorial = 1;while nFactorial<1e100n = n + 1;nFactorial = nFactorial*n.

6 End % control structures terminate with endFurther programming commandsbreakexit the current loop (combine withif)continuego to next iteration (combine withif)try, catchExecute statements and catch errorsSpecial TopicsPolynomialspoly(x)Polynomial with rootsxpoly(A)Characteristic polynomial of matrixpolyeig(x)Polynomial eigenvalue problempolyfit(x,y,d)Polynomial curve fittingresidue(b,a)Partial fraction expansion/decompositionroots(x)Polynomia l rootspolyval(p,x)Evaluate polypat pointsxconv(u,v)Convolution and polynomial multiplicationdeconv(u,v)Deconvolution and polynomial divisionpolyint(p,k)Polynomial integrationpolyder(p)Polynomial differentiationInterpolation and fittinginterp1(x,v,xq)1-D data interpolation (table lookup)interp2(X,Y,V,Xq,Yq)2D interpolation for meshgrid datainterp3(X,..V,..Zq)3D interpolation for meshgrid datapchip(x,v,xq)Piecew. cubic Hermite poly interpolspline(x,v,xq)Cubic spline data interpolationppval(pp,xq)Evaluate piecewise polynomialmkpp(breaks,coeffs)Make piecewise polynomialunmkpp(pp)Extract piecewise polynomial detailsDifferential equationsode45(ode,tspan,y0)Solve system of nonstiff ODEode15s(ode,tspan,y0)Solve system of stiff ODEpdepe(m,pde,ic,bc,xm,ts)Solve 1D PDEspdeval(m,xmesh,usol,xq)Interpolate num.

7 PDE solutionOptimizationfminbnd(fun,x1,x2)Fi nd minimum of fun(x) in [x1,x2]fminsearch(fun,x0)Find minimum of functionlsqnonneg(C,d)Solve non-neg. lin. least-squares (fun,x0)Root of nonlinear functionoptimget(opt, par )Optimization options valuesoptimset( opt ,val)Define optimization optionsDescriptive Statisticsbounds(A)Smallest and largest elementsmax(A)Maximum elements of an arraymin(A)Minimum elements of an arraymode(A)Most frequent values in arraymean(A)Average or mean value of arraymedian(A)Median value of arraystd(A)Standard deviationvar(A)Variancehist(X)calculate and plot histogramcorrcoef(A)Correlation coefficientscov(A)Covariancexcorr(x,y)Cr oss-correlationxcov(x,y)Cross-covariance randUniformly distributed random numbersrandnNormally distributed random numbersrandiUniformly distributed pseudorandom integersfurther functions:movmax, movmin, cummax, cummin,movprod, movsum, cumsum, cumprod, movmean,movmedian, movstd, Mathfactor(n)Prime factorsfactorial(n)Factorial of inputgcd(n,m)Greatest common divisorlcm(n,m)least common multiplemod(a,m)Remainder after division (modulo operation)ceil(X)Round toward positive infinityfix(X)Round toward zerofloor(X)Round toward negative infinityround(X)Round to nearest decimal or integerCheat Sheet for MATLAB Tools Course at ETH Z urich, by Res J ohr


Related search queries