MATLAB® For Dummies®

Visit www.dummies.com/cheatsheet/matlab to view this book's cheat sheet.

Title page image

Appendix A

MATLAB Functions

This appendix provides you with an overview of the MATLAB functions. Each function helps you perform a specific task within MATLAB. The tables contain the function name and a short description of the task that the function performs. If you need more information than this appendix gives you, you can obtain additional information by typing help <function_name> in the MATLAB command window and pressing Enter. Of course, you also have the information found in this book, and you can search in Help. See Chapter 3 for some useful information on using the Help resources that MATLAB provides.

Table A-1 Arithmetic Functions

Function

Description

uplus

Unary plus — comparable to + acting on one object

plus

Plus — comparable to + adding two objects

uminus

Unary minus — comparable to – acting on one object

minus

Minus — comparable to – subtracting two objects

mtimes

Matrix multiplication — comparable to *

times

Array multiply — comparable to .*

rdivide

Right-array division — comparable to ./

mrdivide

Solves systems of linear equations xA = B for x — comparable to /

ldivide

Left-array division — comparable to .\

mldivide

Solves systems of linear equations Ax = B for x — comparable to \

power

Array power — comparable to .^

mpower

Matrix power — comparable to ^

diff

Differences and approximate derivatives

prod

Product of array elements

sum

Sum of array elements

ceil

Rounds toward positive infinity

fix

Rounds toward zero

floor

Rounds toward negative infinity

idivide

Integer division with rounding option

mod

Modulus after division

rem

Remainder after division

round

Rounds to nearest integer

Table A-2 Trigonometric Functions

Function

Description

sin

Sine of argument in radians

sind

Sine of argument in degrees

asin

Inverse sine; result in radians

asind

Inverse sine; result in degrees

sinh

Hyperbolic sine of argument in radians

asinh

Inverse hyperbolic sine

cos

Cosine of argument in radians

cosd

Cosine of argument in degrees

acos

Inverse cosine; result in radians

acosd

Inverse cosine; result in degrees

cosh

Hyperbolic cosine

acosh

Inverse hyperbolic cosine

tan

Tangent of argument in radians

tand

Tangent of argument in degrees

atan

Inverse tangent; result in radians

atand

Inverse tangent; result in degrees

atan2

Four-quadrant inverse tangent

atan2d

Four-quadrant inverse tangent; result in degrees

tanh

Hyperbolic tangent

atanh

Inverse hyperbolic tangent

csc

Cosecant of argument in radians

cscd

Cosecant of argument in degrees

acsc

Inverse cosecant; result in radians

acscd

Inverse cosecant; result in degrees

csch

Hyperbolic cosecant

acsch

Inverse hyperbolic cosecant

sec

Secant of argument in radians

secd

Secant of argument in degrees

asec

Inverse secant; result in radians

asecd

Inverse secant; result in degrees

sech

Hyperbolic secant

asech

Inverse hyperbolic secant

cot

Cotangent of argument in radians

cotd

Cotangent of argument in degrees

acot

Inverse cotangent; result in radians

acotd

Inverse cotangent; result in degrees

coth

Hyperbolic cotangent

acoth

Inverse hyperbolic cotangent

hypot

Square root of sum of squares

Table A-3 Exponentials, Logarithms, Powers, and Roots

Function

Description

exp

Exponential

expm1

Computes exp(x)–1 accurately for small values of x

log

Natural logarithm

log10

Common (base 10) logarithm

log1p

Computes log(1+x) accurately for small values of x

log2

Determines base 2 logarithm and dissect floating-point numbers into exponent and mantissa

nthroot

Real nth root of real numbers

pow2

Base 2 power and scale floating-point numbers

reallog

Natural logarithm for nonnegative real arrays

realpow

Array power for real-only output

realsqrt

Square root for nonnegative real arrays

sqrt

Square root

Table A-4 Complex Number Functions

Function

Description

abs

Absolute value and complex magnitude

angle

Phase angle

complex

Construct complex data from real and imaginary components

conj

Complex conjugate

i

Imaginary unit

imag

Imaginary part of complex number

isreal

Checks whether input is a real array

j

Imaginary unit

real

Real part of complex number

sign

Signum() function, which returns 1 if the corresponding element is greater than 0, 0 if the corresponding element is zero, and –1 if the corresponding element is less than 0.

Table A-5 Discrete Math Functions

Function

Description

factor

Prime factors

factorial

Factorial function

gcd

Greatest common divisor

isprime

Array elements that are prime numbers

lcm

Least common multiple

nchoosek

Binomial coefficient or all combinations

perms

All possible permutations

primes

Generates list of prime numbers

rat, rats

Rational fraction approximation

Table A-6 Polynomial Functions

Function

Description

poly

Polynomial with specified roots

polyder

Polynomial derivative

polyeig

Polynomial eigenvalue problem

polyfit

Polynomial curve fitting

polyint

Integrates the polynomial analytically

polyval

Polynomial evaluation

roots

Polynomial roots

Table A-7 Special Functions

Function

Description

erf

Error function

erfc

Complementary error function

erfcinv

Inverse complementary error function

erfcx

Scaled complementary error function

erfinv

Inverse error function

Table A-8 Cartesian, Polar, and Spherical Functions

Function

Description

cart2pol

Transforms Cartesian coordinates to polar or cylindrical coordinates

cart2sph

Transforms Cartesian coordinates to spherical coordinates

pol2cart

Transforms polar or cylindrical coordinates to Cartesian coordinates

sph2cart

Transforms spherical coordinates to Cartesian coordinates

Table A-9 Constants and Test Matrix Functions

Function

Description

eps

Floating-point relative accuracy

Inf

Infinity

pi

Ratio of circle’s circumference to its diameter

NaN

Not-a-Number

isfinite

Array elements that are finite

isinf

Array elements that are infinite

isnan

Array elements that are NaN

gallery

Test matrices

magic

Magic square

Table A-10 Matrix Operation Functions

Function

Description

cross

Vectors cross product

dot

Vectors dot product

kron

Kronecker tensor product

transpose

Transposes

Table A-11 Linear Equation Functions

Function

Description

inv

Matrix inverse

linsolve

Solves linear system of equations

Table A-12 Eigenvalue Functions

Function

Description

eig

Eigenvalues and eigenvectors

eigs

Largest eigenvalues and eigenvectors of matrix

sqrtm

Matrix square root

Table A-13 Matrix Analysis Functions

Function

Description

det

Matrix determinant

norm

Vector and matrix norms

rank

Rank of matrix

rref

Reduced row echelon form

trace

Sum of diagonal elements

Table A-14 Matrix Functions

Function

Description

expm

Matrix exponential

logm

Matrix logarithm

sqrtm

Matrix square root

arrayfun

Applies function to each element of array

Table A-15 Statistical Functions

Function

Description

corrcoef

Correlation coefficients

cov

Covariance matrix

max

Largest elements in array

mean

Average or mean value of array

median

Median value of array

min

Smallest elements in array

mode

Most frequent values in array

std

Standard deviation

var

Variance

Table A-16 Random Number Generator

Function

Description

rng

Controls random number generation

rand

Uniformly distributed pseudo-random numbers

randn

Normally distributed pseudo-random numbers

randi

Uniformly distributed pseudo-random integers

Table A-17 1-D Interpolation

Function

Description

interp1

1-D data interpolation (table lookup)

Spline

Cubic spline data interpolation

Table A-18 Gridded Data Interpolation

Function

Description

interp2

2-D data interpolation (table lookup)

interp3

3-D data interpolation (table lookup)

interpn

nD data interpolation (table lookup)

griddedInterpolant

Interpolant for gridded data

ndgrid

Rectangular grid in nD space

meshgrid

Rectangular grid in 2D and 3D space

Table A-19 Scattered Data Interpolation

Function

Description

griddata

Interpolates scattered data

Table A-20 Optimization Functions

Function

Description

fminbnd

Finds minimum of single-variable function on fixed intervals

fminsearch

Finds minimum of unconstrained multivariable function using derivative-free method

fzero

Finds root of continuous function of one variable

Table A-21 Ordinary Differential Equation Functions

Function

Description

ode23

Solve nonstiff differential equations; low-order method

Table A-22 Sparse Matrix Manipulation Functions

Function

Description

spy

Visualizes a sparsity pattern

find

Finds indices and values of nonzero elements

Table A-23 Elementary Polygons

Function

Description

polyarea

Area of polygon

inpolygon

Points inside polygonal region

rectint

Rectangle intersection area

Appendix B

MATLAB’s Plotting Routines

This appendix lists the plotting routines in MATLAB with a brief description and example. To save space, some entries show a single encompassing example for multiple commands. An example may also use an ellipsis (...) to show the continuation of a pattern. To assist you, we have included several functions to generate test matrices, for example, rand(), magic(), peaks(), cylinder(), ellipsoid(), and sphere().

Table B-1 Basic Plotting Routines

Routine

Description

Example

ezplot

Plots the expression enclosed in quotes

ezplot('exp(-0.4*x)*sin(x)')

fplot

Same as ezplot, but requires limits

fplot('exp(-0.4*x)*sin(x)',[0,2*pi,-0.3,0.6])

plot

Plots data passed in by vectors

x=[0:2*pi/100:2*pi]; y=exp(-0.4*x).*sin(x);

plot(x,y); figure(2)

comet(x,y); figure(3)

ribbon(x,y);figure(4)

y2=100*exp(-0.4*x).*cos(x);

plotyy(x,y,x,y2)

comet

Just like plot, but comet animates the trajectory. It helps to have a larger vector to slow down the comet trace a tad

ribbon

Like plot, but it displays the data as 3D ribbons

plotyy

Plots data where y values may differ greatly — it makes two y-axes

 

loglog

Plots data on a log scale on both x- and y-axes — y proportional to a power of x is straight on this plot

x=[0:2*pi/100:2*pi]; y=10*x.^pi;

loglog(x,y)

semilogx

X-axis data is on a log scale and the y-axis is on a linear scale — y linearly related to log(x) is straight on this plot

x=[0:2*pi/100:2*pi]; y=10*log(x)+pi;

semilogx(x,y);

semilogy

Y-axis data is on a log scale and x-axis linear — y proportional to exponential of x is straight on this plot

x=[0:2*pi/100:2*pi]; y=10*exp(pi*x);

semilogy(x,y);

Table B-2 Beyond Basics

Routine

Description

Example

area

Acts just like plot except for the fact that it fills in the area for you

x=[0:2*pi/100:2*pi];

y=exp(-0.4*x).*sin(x);

area(x,y)

pie

Creates a standard pie chart

x=[2,4,6,8];

pie(x); figure(2)

pie3(x)

pie3

Adds some 3D pizazz to pie

 

ezpolar

Creates a polar plot where the distance from origin vs. angle is plotted — argument is function expression

ezpolar('cos(2*x)^2');

polar

Creates a polar plot like ezpolar but does so by accepting vector arguments — x value corresponds to angle and y value to distance from origin

x=[0:2*pi/100:2*pi];

y=(exp(-0.1*x).*sin(x)).^2;

polar(x,y)

compass

Like polar, but compass shows data as vectors from origin

compass(rand(1,3)-0.5,...

rand(1,3)-0.5)

bar

Creates a standard bar chart that can handle both grouping and stacking

x=[8,7,6;13,21,15;32,27,32];

bar(x); figure(2)

y=sum(x,2);

bar(y); figure(3)

bar(x,'stacked'); figure(4)

barh(x); figure(5)

bar3(x); figure(6)

bar3h(x)

barh

Just like bar except plot is horizontal

bar3

Adds a little 3D pizazz to a standard bar chart

bar3h

Creates a 3D horizontal bar chart

 

fill

Fills polygons (vector inputs define vertices) with the specified color

y=sin([0:2*pi/5:2*pi])

x=cos([0:2*pi/5:2*pi])

fill(x,y,'g')

Table B-3 Statistical Plotting Routines

Routine

Description

Example

scatter

Plots (x,y) data points.

x=[0:2*pi/100:2*pi]; y=10*x+pi+10*randn(1,101);

scatter(x,y); figure(2)

stem(x,y); figure(3)

errorbar(x,y,10*ones(1,101),ones(1,101))

figure(4);

hist(y); figure(5)

histogram(y)

histc(y,[-40:20:80])

histcounts(y,5)

stem

Like scatter, but adds a line from the x axis to a data point.

errorbar

Like scatter but adds error bars.

hist or histogram

Creates a histogram — a bar chart showing the frequency of occurrence of data vs. value. These two routines handle the bins differently.

 

histc

Related to hist, but rather than making a plot, it makes a vector of counts.

histc(y,[-40:20:80]) example with histc category

histcounts

Like histc except it creates n bins.

histcounts(y,5) example with histcounts category

stairs

Like scatter, but makes stairsteps when y values change.

x=[0:2*pi/10:2*pi]; y=10*x+pi+10*randn(1,11);

stairs(x,y)

rose

A cross between polar and histogram; it displays frequency vs. angle.

rose(randn(1,100),5)

pareto

A bar chart arranged with the highest bars first.

histc(randn(1,100),[-4:1:4])

pareto(ans)

spy

A scatter plot of zeros in a matrix.

mymat=rand(5); mymat=(mymat>0.5).*mymat;

spy(mymat)

plotmatrix

A scatter plot of all permutations of columns of x and y.

plotmatrix(magic(3),magic(3))

Table B-4 3D Graphics

Routine

Description

Example

ezcontour

Makes a contour plot like a topographic map

ezcontour('cos(x)*cos(y)')

ezcontourf

Same as ezcontour except it fills in the area between contours

ezcontourf('cos(x)*cos(y)')

ezmesh

Creates a 3D perspective plot with an open wireframe mesh

ezmesh('cos(x)*cos(y)')

ezsurf

Creates a 3D perspective plot with a filled surface

ezsurf('cos(x)*cos(y)')

ezmeshc

Combines a contour plot with mesh

ezmeshc('cos(x)*cos(y)')

ezsurfc

Combines a contour plot with a 3D perspective filled surface plot

ezsurfc('cos(x)*cos(y)')

ezplot3

Plots a curve in 3D space; capable of being animated

ezplot3('sin(x)','cos(x)','sin(3*x/2)',...

[-2*pi,2*pi],'animate')

plot3

Like ezplot3, except it takes vector arguments

a=[-2*pi:4*pi/100:2*pi];

x=sin(a); y=cos(a); z=sin(3*a/2);

plot3(x,y,z); figure(2)

scatter3(x,y,z)

scatter3

Like plot3, but shows individual points

 

stem3

Stem plot of 3D data

stem3(rand(5))

contour

Creates a contour plot with matrix arguments

x=[-2*pi:4*pi/100:2*pi];

y=[-2*pi:4*pi/100:2*pi];z=cos(x)'*cos(y);

contour(x,y,z);title('contour');figure(2)

contourf(x,y,z);title('contourf');figure(3)

contour3(x,y,z);title('contour3');figure(4)

surf(x,y,z);title('surf');figure(5)

surface(x,y,z);title('surface');figure(6)

mesh(x,y,z);title('mesh');figure(7)

waterfall(x,y,z);title('waterfall');figure(8)

surfc(x,y,z);title('surfc');figure(9)

meshc(x,y,z);title('meshc');figure(10)

meshz(x,y,z);title('meshz');figure(11)

surfl(x,y,z);title('surfl');figure(12)

pcolor(z);title('surfl')

contourf

Same as contour, except contourf fills in the contours

contour3

Same as contour, except contour3 provides a 3D perspective

surf or surface

Creates a filled surface

mesh

Creates a wireframe mesh surface

waterfall

Like mesh, but all column lines are omitted

surfc

Same as surf, but with contour plot added

meshc

Wireframe mesh with contour

meshz

Wireframe mesh with a curtain around the plot

surfl

Same as surf, except surfl simulates light and shadow

pcolor

Shows values of the matrix as colors

 

surfnorm

Creates surface plot with normal vectors

[x,y,z]=peaks; % Test function

surfnorm(x,y,z)

fill3

Like fill except in 3D; note that the fill area may not be coplanar

fill3([0,1,1,0],[0,0,1,0],[0,1,0,1],'g')

Table B-5 Vector Fields

Routine

Description

Example

feather

Like compass except it steps once for each element in x and y

feather(rand(1,3)-0.5,...

rand(1,3)-0.5)

quiver

Works like feather except quiver plots vectors in an x-y plane

[x,y]=meshgrid([-5:5],[-5:5]);

u=ones(11)+(4./(sqrt(x.^2+y.^2)).*cos(atan2(y,x)));

v=(4./(sqrt(x.^2+y.^2)).*sin(atan2(y,x)));

v(6,6)=0; u(6,6)=0;

quiver(x,y,u,v); hold on

streamline(x,y,u,v,[-5,-5,-5],[-1,.01,1]); hold off, figure(2)

streamline

Plots line from the vector field; the example plots 2D streamline on the same plot as quiver

 

quiver3

Like quiver for 3D; the example adds a uniform velocity field to a 1/r2 velocity field

[x,y,z]=meshgrid([-5:2:3],[-3:2:3],[-3:2:3]);

r=sqrt(x.^2+y.^2+z.^2);

u=ones(4,5,4)+(10./r.^2).*cos(atan2(y,x)).*sin(acos(z./r));

v=(10./r.^2).*sin(atan2(y,x)).*sin(acos(z./r));

w=10.*z./r; quiver3(x,y,z,u,v,w);hold on;

streamribbon(x,y,z,u,v,w,-5,0,.1);figure(2)

coneplot(x,y,z,u,v,w,x,y,z);figure(3)

quiver3(x,y,z,u,v,w);hold on;

streamtube(x,y,z,u,v,w,-5,0,.1);

streamribbon

Like streamline, but shows ribbons

coneplot

Like quiver3, but coneplot shows velocity as cones

streamtube

Like streamline, but plots tubes (cylindrical 3D flow lines)