0% found this document useful (0 votes)
327 views

MATLAB Fundamentals - Cheat Sheet - Tools Course ETH Z Urich

This document provides a cheat sheet summarizing key MATLAB fundamentals including the basics of the MATLAB workspace, arithmetic operations, numerical and linear algebra functions, matrix manipulation, and common constants. It covers topics such as basic commands, variables, matrices, elementwise and matrix operations, integration, differentiation, eigenvalues, and linear solvers.

Uploaded by

Paul Okewunmi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
327 views

MATLAB Fundamentals - Cheat Sheet - Tools Course ETH Z Urich

This document provides a cheat sheet summarizing key MATLAB fundamentals including the basics of the MATLAB workspace, arithmetic operations, numerical and linear algebra functions, matrix manipulation, and common constants. It covers topics such as basic commands, variables, matrices, elementwise and matrix operations, integration, differentiation, eigenvalues, and linear solvers.

Uploaded by

Paul Okewunmi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

MATLAB Fundamentals - Cheat Sheet - Tools Course ETH Zürich

Basics Arithmetics 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,c,d) 2D num. integration
clear var clear variables Workspace A./B elementwise division integral3(f,a,b,..,r,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)
help fun open in-line help prod(X) Product of elements (along columns)
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 .. det(A) determinant of A
iskeyword arg Check if arg is keyword Elementary Functions
sin(A) Sine of argument in radians eig(A),eigs(A) eigenvalues of A (subset)
% This is a comment Comments cross(A,B) Cross product
... connect lines (with break) sind(A) Sine of argument in degrees
asin(A) Inverse sine in radians dot(A,B) Dot product
";" (after command) suppresses output kron(A,B) Kronecker tensor product
scriptname runs scriptname.m sinh(A) Hyperbolic sine
there are analogous elementwise trigonometric functions norm(x) Vector and matrix norms
tic, toc start and stop timer linsolve(A,B) Solve linear system of equations
ver List of installed toolboxes for cos, tan and cot
rank(A) Rank of matrix
MATLAB Documentation: mathworks.com/help/matlab/ abs(A) Compute |x|
√ 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)
Defining and Changing Variables divergence(X,..,W) Compute divergence of vector field
log10(x) Compute log10 (x)
a = 5 Define variable a to be 5 null(A) Null space of matrix
sign(x) sign of x
A = [1, 2, 3, 4; Set A to be a 3 × 4 matrix orth(A) Orthonormal basis for matrix range
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
[A;B], vertcat(A,B) Concatenate arrays vertically lsqminnorm(A,B) Least-squares solution to linear eq.
Complex Numbers
x(2) = 7 Change 2nd element of x to 7 rref(A) Reduced row echelon form
abs(z) Absolute value and complex magnitude
A(2,1) = 0 Change A2,1 to 0 balance(A) Diagonal scaling (improve eig. vec.)
angle(z) Phase angle
x(2:12) The 2nd to the 12th elem. of x svd(A) Singular value decomposition
complex(a,b) Create complex numbers
x(1:3:end) Every 3rd elem. of x (1st to last) gsvd(A,B) Generalized svd
conj(z) Elementwise complex conjugate
x(x>6) List elements > 6. chol(A) Cholesky factorization
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ürich, by Res Jöhr
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
if n<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 elseif n<20
disp('n between 10 and 20')
xlim /ylim / zlim get or set axes range else
Differential equations
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('Enter a number: ');
switch n
case -1 Optimization
disp('negative one') fminbnd(fun,x1,x2) Find minimum of fun(x) in [x1 , x2 ]
case 0
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')
otherwise
fzero(fun,x0) Root of nonlinear function
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
%loop a 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
disp('cool'); % comment with some LATEXin it: πx2
end % control structures terminate with end
mode(A) Most frequent values in array
mean(A) Average or mean value of array
While-Loop median(A) Median value of array
%loops as long as a condition remains true std(A) Standard deviation
n = 1; var(A) Variance
nFactorial = 1;
while nFactorial < 1e100
hist(X) calculate and plot histogram
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 integers
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.
poly(x) Polynomial with roots x
Programming methods poly(A) Characteristic polynomial of matrix Discrete Math
Functions polyeig(x) Polynomial eigenvalue problem factor(n) Prime factors
% defined in m-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 divisor
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) Remainder after division (modulo 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 integer

Cheat Sheet for MATLAB Tools Course at ETH Zürich, by Res Jöhr

You might also like