Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Matlab Basic Functions Reference

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4
At a glance
Powered by AI
This document discusses many common MATLAB functions and commands for manipulating variables, arrays, matrices, and performing mathematical operations.

Common MATLAB commands include tic/toc for timing, clc to clear the command window, help for getting documentation, and load/save for loading and saving variables.

Arrays can be defined using brackets [], concatenated using brackets and commas or semicolons, and elements can be accessed or changed using subscript notation. Functions like zeros, ones, rand can create arrays.

MATLAB® Basic Functions Reference

MATLAB Environment Defining and Changing Array Variables


clc Clear command window a = 5 Define variable a with value 5
help fun Display in-line help for fun A = [1 2 3; 4 5 6] Define A as a 2x3 matrix
doc fun A = [1 2 3 “space” separates columns
Open documentation for fun
4 5 6] “;” or new line separates rows
load("filename","vars") Load variables from .mat file
[A,B] Concatenate arrays horizontally
uiimport("filename") Open interactive import tool
[A;B] Concatenate arrays vertically
save("filename","vars") Save variables to file
x(4) = 7 Change 4th element of x to 7
clear item Remove items from workspace
A(1,3) = 5 Change A(1,3) to 5
examplescript Run the script file named
x(5:10) Get 5th to 10th elements of x
examplescript
format style x(1:2:end) Get every 2nd element of x (1st to last)
Set output display format
ver x(x>6) List elements greater than 6
Get list of installed toolboxes
x(x==10)=1 Change elements using condition
tic, toc Start and stop timer
A(4,:) Get 4th row of A
Ctrl+C Abort the current calculation
A(:,3) Get 3rd column of A
Operators and Special Characters A(6, 2:5) Get 2nd to 5th element in 6th row of A

+, -, *, / A(:,[1 7])=A(:,[7 1]) Swap the 1st and 7th column


Matrix math operations
.*, ./ a:b [a, a+1, a+2, …, a+n] with a+n≤b
Array multiplication and division
(element-wise operations) a:ds:b Create regularly spaced vector with
^, .^ Matrix and array power spacing ds

\ linspace(a,b,n) Create vector of n equally spaced values


Left division or linear optimization
.', ' logspace(a,b,n) Create vector of n logarithmically spaced
Normal and complex conjugate
transpose values

==, ~=, <, >, <=, >= 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

Special Variables and Constants Complex Numbers


ans Most recent answer i, j, 1i, 1j Imaginary unit
pi π=3.141592654… real(z) Real part of complex number
i, j, 1i, 1j Imaginary unit imag(z) Imaginary part of complex number
NaN, nan Not a number (i.e., division by zero) angle(z) Phase angle in radians
Inf, inf Infinity conj(z) Element-wise complex conjugate
eps Floating-point relative accuracy isreal(z) Determine whether array is real

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

Tasks (Live Editor)


Live Editor tasks are apps that can be added to a live script to interactively
perform a specific set of operations. Tasks represent a series of MATLAB
commands. To see the commands that the task runs, show the generated
code.

Common tasks available from the Live Editor tab on the


desktop toolstrip:
• Clean Missing Data • Clean Outlier
• Find Change Points • Find Local Extrema
Plot Gallery: mathworks.com/products/matlab/plot-gallery
• Remove Trends • Smooth Data

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

Control Structures diff(X) Differences and approximate derivatives


gradient(X) Numerical gradient
if, elseif Conditions
curl(X,Y,Z,U,V,W) Curl and angular velocity
if n<10
disp("n smaller 10") divergence(X,..,W) Compute divergence of
elseif n<=20 vector field
disp("n between 10 and 20")
ode45(ode,tspan,y0) Solve system of nonstiff ODEs
else
disp("n larger than 20") ode15s(ode,tspan,y0) Solve system of stiff ODEs
Switch Case deval(sol,x) Evaluate solution of differential equation
n = input("Enter an integer: "); pdepe(m,pde,ic,... Solve 1D partial differential equation
switch n bc,xm,ts)
case -1 pdeval(m,xmesh,... Interpolate numeric PDE solution
disp("negative one") usol,xq)
case {0,1,2,3} % check four cases together
disp("integer between 0 and 3")
otherwise Interpolation and Polynomials
disp("integer value outside interval [-1,3]")
end % control structures terminate with end interp1(x,v,xq) 1D interpolation
(analogous for 2D and 3D)
For-Loop
pchip(x,v,xq) Piecewise cubic Hermite polynomial
% loop a specific number of times, and keep
interpolation
% track of each iteration with an incrementing
% index variable spline(x,v,xq) Cubic spline data interpolation
for i = 1:3 ppval(pp,xq) Evaluate piecewise polynomial
disp("cool");
mkpp(breaks,coeffs) Make piecewise polynomial
end % control structures terminate with end
unmkpp(pp) Extract piecewise polynomial details
While-Loop
poly(x) Polynomial with specified roots x
% loops as long as a condition remains true
n = 1; polyeig(A0,A1,...,Ap) Eigenvalues for polynomial eigenvalue
nFactorial = 1; problem
while nFactorial < 1e100 polyfit(x,y,d) Polynomial curve fitting
n = n + 1;
nFactorial = nFactorial * n; residue(b,a) Partial fraction expansion/decomposition
end % control structures terminate with end roots(p) Polynomial roots
polyval(p,x) Evaluate poly p at points x
Further programming/control commands
break polyint(p,k) Polynomial integration
Terminate execution of for- or while-loop
continue polyder(p) Polynomial differentiation
Pass control to the next iteration of a loop
try, catch Execute statements and catch errors

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

rref(A) int(expr,var,[a, b]) Integrate symbolic expression


Reduced row echelon form of matrix
taylor(fun,var,z0) Taylor expansion of function

*requires Symbolic Math Toolbox

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.

You might also like