<<

MATLAB Fundamentals - Cheat Sheet - Tools Course ETH Z¨urich

Basics Numerics and Linear Algebra Workspace +, - Addition, Subtraction (elementwise) Numerical Integration and Differentiation ans Most recent answer A*B Matrix multiplication integral(f,a,b) Numerical integration clc clear command window A.*B elementwise multiplication integral2(f,a,b,,) 2D num. integration clear var clear variables Workspace A./B elementwise integral3(f,a,b,..,,s) 3D num. integration clf Clear all plots B.\A Left array division trapz(x,y) Trapezoidal integration close all Close all plots / Solve xA = B for x cumtrapz(x,y) Cumulative trapez integration ctrl-c Kill the current calculation \ Solve Ax = B for x diff(X) Differences (along columns) ∧ doc fun open documentation A n normal/(square) matrix power gradient(X) Numerical gradient ∧ disp(’text’) Print text A. n Elementwise power of A format short—long Set output display format sum(X) Sum of elements (along columns) prod(X) Product of elements (along columns) help fun open in-line help Matrix Functions/ Linear Algebra load filename {vars} load variables from .mat file A’ Transpose of matrix or vector save {-append} file {vars} save var to file inv(A) inverse of A (use with care!) addpath path include path to .. Elementary Functions det(A) determinant of A iskeyword arg Check if arg is keyword eig(A),eigs(A) eigenvalues of A (subset) % This is a comment Comments sin(A) Sine of argument in radians sind(A) Sine of argument in degrees cross(A,B) Cross product ... connect lines (with break) dot(A,B) Dot product ";" (after command) suppresses output asin(A) Inverse sine in radians sinh(A) Hyperbolic sine kron(A,B) Kronecker scriptname runs scriptname.m norm(x) Vector and matrix norms tic, toc start and stop timer there are analogous elementwise trigonometric functions for cos, tan and cot linsolve(A,B) Solve linear system of equations ver List of installed toolboxes rank(A) Rank of matrix abs(A) Compute |x| MATLAB Documentation: mathworks.com/help/matlab/ √ trace(A) Sum of diagonal elements sqrt(x) Compute x curl(X,Y,Z,U,V,W) Curl and angular velocity log(x) Compute ln(x) divergence(X,..,W) Compute divergence of vector field Defining and Changing Variables log10(x) Compute log (x) 10 null(A) Null space of matrix a = 5 Define variable a to be 5 sign(x) sign of x orth(A) Orthonormal basis for matrix range A = [1, 2, 3, 4; Set A to be a 3 × 4 matrix exp(x) exponential of x 5, 6, 7, 8; ”,” separates columns mldivide(A,B) Solve linear system Ax = B for x 9, 10, 11, 12] ”;” separates rows mrdivide(B,A) Solve linear system xA = B for x [A,B], horzcat(A,B) Concatenate arrays horizontally decomposition(A) Matrix decomposition Least-squares solution to linear eq. [A;B], vertcat(A,B) Concatenate arrays vertically Complex Numbers lsqminnorm(A,B) rref(A) Reduced row echelon form x(2) = 7 Change 2nd element of x to 7 abs(z) Absolute value and complex magnitude balance(A) Diagonal scaling (improve eig. vec.) A(2,1) = 0 Change A2,1 to 0 angle(z) Phase angle svd(A) Singular value decomposition x(2:12) The 2nd to the 12th elem. of x complex(a,b) Create complex numbers gsvd(A,B) Generalized svd x(1:3:end) Every 3rd elem. of x (1st to last) conj(z) Elementwise complex conjugate chol(A) Cholesky factorization x(x>6) List elements > 6. i or j Imaginary unit x(x>8)=8 change elements using condition imag(z) Imaginary part of complex number A(4,:) Get the 4th row of A isreal(z) Determine whether array is real A(:,3) Get the 3rd column of A real(z) Real part of complex number Matrix manipulation A(6, 1:3) Get 1st to 3rd elem in 6th row ctranspose(Z) Complex conjugate transpose cat(dim,A,B) Concatenate arrays zeros(9, 5) Make a 9 × 5 matrix of zeros ndims(A) Number of array dimensions ones(9, 5) Make a 9 × 5 matrix of ones flip(A) Flip order of elements eye(7) Make a 7 × 7 identity matrix fliplr(A) Flip array left to right diag(x) Create diagonal matrix Constants flipud(A) Flip array up to down diag(A) Get diagonal elements of matrix pi π = 3.141592653589793 squeeze(A) Remove dimensions of length 1 meshgrid(x) 2-D and 3-D grids NaN Not a number (i.e. 0/0) reshape(A,sz) Reshape array 7:15 Row vector of 7, 8,..., 14, 15 Inf Infinity size(A) size of A a:ds:b lin. spaced vector with spacing ds eps Floating-point relative accuracy sort(A) Sort array elements linspace(1,20,35) Lin. spaced vector (35 elements) realmax Largest positive floating-point number sortrows(A) Sort rows of matrix or table logspace(1, 1e5, 50) Log. spaced vector (50 elements) realmin Smallest positive floating-point number length(A) Length of largest array dimension

Cheat Sheet for MATLAB Tools Course at ETH Z¨urich, by Res J¨ohr Graphics Relational and logical operations Interpolation and fitting Plotting == Check equality ∼= Check inequality interp1(x,v,xq) 1-D data interpolation (table lookup) plot(x,y) Plot y vs. x > greater than >= greater or equal to interp2(X,Y,V,Xq,Yq) 2D interpolation for meshgrid data axis equal Scale axes equally < less than <= less or equal to interp3(X,..V,..Zq) 3D interpolation for meshgrid data title(’A Title’) Add title to the plot &, && logical AND ∼ logical NOT pchip(x,v,xq) Piecew. cubic Hermite poly interpol xlabel(’x axis’) Add label to the x axis |, | | logical OR xor logical exclusive-OR spline(x,v,xq) Cubic spline data interpolation ylabel(’y axis’) Add label to the y axis if, elseif Conditions ppval(pp,xq) Evaluate piecewise polynomial legend(’foo’, ’bar’) Label 2 curves for the plot mkpp(breaks,coeffs) Make piecewise polynomial ifn <10 grid Add a grid to the plot disp('n smaller 10') unmkpp(pp) Extract piecewise polynomial details hold on / off Multiple plots on single figure elseifn <20 disp('n between 10 and 20') Differential equations xlim /ylim / zlim get or set axes range else figure Start a new plot disp('n larger than 20') ode45(ode,tspan,y0) Solve system of nonstiff ODE Plot types end% control structures terminate with end ode15s(ode,tspan,y0) Solve system of stiff ODE Switch Case pdepe(m,pde,ic,bc,xm,ts) Solve 1D PDEs pdeval(m,xmesh,usol,xq) Interpolate num. PDE solution n = input('Entera number:'); switchn case -1 Optimization disp('negative one') fminbnd(fun,x1,x2) Find minimum of fun(x) in [x1, x2] case0 disp('zero') fminsearch(fun,x0) Find minimum of function case {1,2,3} %check three cases together lsqnonneg(C,d) Solve non-neg. lin. least-squares prob. disp('positive one') fzero(fun,x0) Root of nonlinear function otherwise disp('other value') optimget(opt,’par’) Optimization options values end% control structures terminate with end optimset(’opt’,val) Define optimization options For-Loop Descriptive Statistics %loopa specific number of times, and keep track of each ... iteration with an incrementing index variable bounds(A) Smallest and largest elements %parfor might be used to parallelize the execution max(A) Maximum elements of an array for i = 1:3 min(A) Minimum elements of an array 2 disp('cool');% comment with someL ATEXin it: πx Most frequent values in array end% control structures terminate with end mode(A) mean(A) Average or mean value of array While-Loop median(A) Median value of array %loops as long asa condition remains true std(A) Standard deviation n = 1; var(A) Variance nFactorial = 1; hist(X) calculate and plot histogram while nFactorial < 1e100 n = n + 1; corrcoef(A) Correlation coefficients nFactorial = nFactorial * n; cov(A) Covariance end% control structures terminate with end xcorr(x,y) Cross-correlation Further programming commands xcov(x,y) Cross-covariance break exit the current loop (combine with if) rand Uniformly distributed random numbers continue go to next iteration (combine with if) randn Normally distributed random numbers try, catch Execute statements and catch errors randi Uniformly distributed pseudorandom further functions: movmax, movmin, cummax, cummin, Plot gallery: mathworks.com/products/matlab/plot-gallery Special Topics movprod, movsum, cumsum, cumprod, movmean, Polynomials movmedian, movstd, movvar. Programming methods poly(x) Polynomial with roots x poly(A) Characteristic polynomial of matrix Discrete Math Functions polyeig(x) Polynomial eigenvalue problem factor(n) Prime factors % defined inm-file polyfit(x,y,d) Polynomial curve fitting factorial(n) Factorial of input % File must have the same name as the function residue(b,a) Partial fraction expansion/decomposition gcd(n,m) Greatest common function output = addNumbers(x, y) roots(x) Polynomial roots lcm(n,m) least common multiple output = x + y;%multiple or var nr of args possible end polyval(p,x) Evaluate poly p at points x mod(a,m) after division ( operation) conv(u,v) Convolution and polynomial multiplication ceil(X) Round toward positive infinity Anonymous Functions deconv(u,v) Deconvolution and polynomial division fix(X) Round toward zero % defined via function handles polyint(p,k) Polynomial integration floor(X) Round toward negative infinity f = @(x) cos(x.ˆ2)./(3*x); polyder(p) Polynomial differentiation round(X) Round to nearest decimal or

Cheat Sheet for MATLAB Tools Course at ETH Z¨urich, by Res J¨ohr