Matlab Basic Functions Reference
Matlab Basic Functions Reference
Matlab Basic Functions Reference
==, ~=, <, >, <=, >= zeros(m,n) Create m x n matrix of zeros
Relational operators
ones(m,n) Create m x n matrix of ones
&&, ||, ~, xor Logical operations
(AND, NOT, OR, XOR) eye(n) Create a n x n identity matrix
; Suppress output display A=diag(x) Create diagonal matrix from vector
... Connect lines (with break) x=diag(A) Get diagonal elements of matrix
% Description Comment meshgrid(x,y) Create 2D and 3D grids
'Hello' Definition of a character vector rand(m,n), randi Create uniformly distributed random
"This is a string" numbers or integers
Definition of a string
randn(m,n) Create normally distributed random
str1 + str2 Append strings
numbers
mathworks.com/help/matlab
Elementary Functions Plotting
sin(x), asin Sine and inverse (argument in radians) plot(x,y,LineSpec) Plot y vs. x
Line styles: (LineSpec is optional)
sind(x), asind Sine and inverse (argument in degrees)
-, --, :, -. LineSpec is a combination of
sinh(x), asinh Hyperbolic sine and inverse (arg. in Markers: linestyle, marker, and
radians) +, o, *, ., x, s, d color as a string.
Analogous for the other trigonometric functions: Colors: Example: "-r"
cos, tan, csc, sec, and cot r, g, b, c, m, y, k, w = red solid line without markers
abs(x) Absolute value of x, complex magnitude title("Title") Add plot title
exp(x) Exponential of x legend("1st", "2nd") Add legend to axes
sqrt(x), nthroot(x,n) Square root, real nth root of real numbers x/y/zlabel("label") Add x/y/z axis label
log(x) Natural logarithm of x x/y/zticks(ticksvec) Get or set x/y/z axis ticks
log2(x), log10 Logarithm with base 2 and 10, respectively x/y/zticklabels(labels) Get or set x/y/z axis tick labels
factorial(n) Factorial of n x/y/ztickangle(angle) Rotate x/y/z axis tick labels
sign(x) Sign of x x/y/zlim Get or set x/y/z axis range
mod(x,d) Remainder after division (modulo) axis(lim), axis style Set axis limits and style
ceil(x), fix, floor Round toward +inf, 0, -inf text(x,y,"txt") Add text
round(x) Round to nearest decimal or integer grid on/off Show axis grid
hold on/off Retain the current plot when
adding new plots
Tables subplot(m,n,p), Create axes in tiled positions
table(var1,...,varN) Create table from data in variables tiledlayout(m,n)
var1, ..., varN yyaxis left/right Create second y-axis
readtable("file") Create table from file figure Create figure window
array2table(A) Convert numeric array to table gcf, gca Get current figure, get current axis
T.var Extract data from variable var clf Clear current figure
T(rows,columns), Create a new table with specified close all Close open figures
T(rows,["col1","coln"]) rows and columns from T
T.varname=data Assign data to (new) column in T Common Plot Types
T.Properties Access properties of T
categorical(A) Create a categorical array
summary(T), groupsummary Print summary of table
join(T1, T2) Join tables with common variables
mathworks.com/help/matlab
Programming Methods Numerical Methods
Functions fzero(fun,x0) Root of nonlinear function
% Save your function in a function file or at the end fminsearch(fun,x0) Find minimum of function
% of a script file. Function files must have the
fminbnd(fun,x1,x2) Find minimum of fun in [x1, x2]
% same name as the 1st function
function cavg = cumavg(x) %multiple args. possible fft(x), ifft(x) Fast Fourier transform and its inverse
cavg=cumsum(vec)./(1:length(vec));
end
Integration and Differentiation
Anonymous Functions
% defined via function handles integral(f,a,b) Numerical integration
fun = @(x) cos(x.^2)./abs(3*x); (analogous functions for 2D and 3D)
trapz(x,y) Trapezoidal numerical integration
mathworks.com/help/matlab
Matrices and Arrays Descriptive Statistics
length(A) Length of largest array dimension sum(A), prod Sum or product (along columns)
size(A) Array dimensions max(A), min, bounds Largest and smallest element
numel(A) Number of elements in array mean(A), median, mode Statistical operations
sort(A) Sort array elements std(A), var Standard deviation and variance
sortrows(A) Sort rows of array or table movsum(A,n), movprod, Moving statistical functions
movmax, movmin, n = length of moving window
flip(A) Flip order of elements in array
movmean, movmedian,
squeeze(A) Remove dimensions of length 1 movstd, movvar
reshape(A,sz) Reshape array cumsum(A), cumprod, Cumulative statistical functions
repmat(A,n) cummax, cummin
Repeat copies of array
smoothdata(A) Smooth noisy data
any(A), all Check if any/all elements are nonzero
nnz(A) histcounts(X) Calculate histogram bin counts
Number of nonzero array elements
find(A) corrcoef(A), cov Correlation coefficients, covariance
Indices and values of nonzero elements
xcorr(x,y), xcov Cross-correlation, cross-covariance
normalize(A) Normalize data
Linear Algebra
detrend(x) Remove polynomial trend
rank(A) Rank of matrix
isoutlier(A) Find outliers in data
trace(A) Sum of diagonal elements of matrix
det(A) Determinant of matrix
poly(A) Characteristic polynomial of matrix
Symbolic Math*
eig(A), eigs Eigenvalues and vectors of matrix (subset) sym x, syms x y z Declare symbolic variable
inv(A), pinv Inverse and pseudo inverse of matrix eqn = y == 2*a + b Define a symbolic equation
norm(x) Norm of vector or matrix solve(eqns,vars) Solve symbolic expression
for variable
expm(A), logm Matrix exponential and logarithm
subs(expr,var,val) Substitute variable in expression
cross(A,B) Cross product
expand(expr) Expand symbolic expression
dot(A,B) Dot product
factor(expr) Factorize symbolic expression
kron(A,B) Kronecker tensor product
simplify(expr) Simplify symbolic expression
null(A) Null space of matrix
assume(var,assumption) Make assumption for variable
orth(A) Orthonormal basis for matrix range
assumptions(z) Show assumptions for
tril(A), triu Lower and upper triangular part of matrix
symbolic object
linsolve(A,B) Solve linear system of the form AX=B fplot(expr), fcontour, Plotting functions for
lsqminnorm(A,B) Least-squares solution to linear equation fsurf, fmesh, fimplicit symbolic expressions
qr(A), lu, chol Matrix decompositions diff(expr,var,n) Differentiate symbolic expression
svd(A) Singular value decomposition dsolve(deqn,cond) Solve differential
gsvd(A,B) Generalized SVD equation symbolically
mathworks.com/help/matlab
© 2021 The MathWorks, Inc. MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks.
Other product or brand names may be trademarks or registered trademarks of their respective holders.