Sunteți pe pagina 1din 99

# MATLAB

introduction

## We cannot teach people anything.

We can only help them discover it within themselves.
Galileo Galilei
Why this Course?
The computer:
 indispensable tool used in
all aspects of the sciences.
 perform time consuming
 the single most important
instrument you need to
PDVWHUDOORZLQJ\RXWR«
± Visualize, explore, and
± Develop models to explain
± Simulate phenomena
± ...
CourseIntroduction_3

##  Check Job DG¶V

 Tiobe index

CourseIntroduction_4
Goals

##  Aim: getting to know the basics Matlab

± Introduce Matlab to the novice
± Illustrate key features and capabilities of Matlab
± Understand basic Matlab code
± Demonstrate to write efficient Matlab code
 Matlab programming and C
± Syntax is similar
± language structure is similar to C:
 Matlab supports variables, arrays, structures, subroutines, files
 Matlab does not support pointers and does not require variable
declarations

CourseIntroduction_5

Goals

##  Matlab is an extensive package, you will not be able to

know all functions
± Matlab documentation: more than 5000 pages
± More than 300 built-in functions
± More than 1000 M-files contained in the base product of Matlab
± ...
 Matlab is the SWISS ARMY KNIFE for numerical
problems

CourseIntroduction_6
www.mathworks.com
Statistics Application development
Optimization tools:
Signal processing Matlab compiler
Matlab Excel builder
Image processing Matlab Com builder
Curve fitting Data acquisition and access
Bioinformatics toolbox tools
.... Data acquisition toolbox....
Database toolbox

CourseIntroduction_7

##  Engineering and scientific applications involve a lot of

"number crunching".
 For many years, the main language for this was
FORTRAN
 Here's a Fortran code to solve a x2 + b x + c = 0:
C Solve a quadratic equation (this is a comment).
DESC = B*B - 4*A*C
IF ( DESC .LT. 0.0 ) GOTO 10
DESC = SQRT(DESC)
X1 = (-B + DESC)/(2.0*A)
X2 = (-B - DESC)/(2.0*A)
WRITE(6,*) "SOLUTIONS ARE ",X1," AND ", X2
RETURN
10 WRITE(6,*) "EQUATION HAS COMPLEX ROOTS"
RETURN CourseIntroduction_8
Solving a Linear System in Fortran
Here's a Fortran code to solve a linear system A.x=b, solve
for x.

## C Solve B = A*X for X. C... Backwards substitution

C N is dimension of vectors and matrix X(N) = X(N)/A(N,N)
C Does not use row interchange, scaling. DO 21 I=N-1,1,-1
SUBROUTINE LINSYS(N, A, X, B, TMP) TMP = X(I)
INTEGER N DO 20 J=I+1,N
DOUBLE PRECISION A(N,N), X(N), B(N) 20 TMP = TMP - A(I,J)*X(J)
DOUBLE PRECISION TMP(N), RATIO X(I) = TMP/A(I,I)
C... Forward elimination 21 CONTINUE
DO 13 J=1,N-1 RETURN
DO 12 I=J+1,N END
RATIO = -A(I,J)/A(J,J)
A(I,*) = A(I,*) +RATIO*ROW(J,*)
DO 11 K=J+1,N This is just a small example.
11 A(I,K) = A(I,K) + RATIO*A(J,K)
A(I,J) = 0.0 A full program may be 1000's of
X(I) = X(I) + RATIO*X(J)
12 CONTINUE
lines long.
11 CONTINUE
Continued...

CourseIntroduction_9

##  The U.S. government recognized these problems, and

the inefficiency of many engineers all writing the same
algorithms... again and again.
 So, they commissioned numerical analysts to write
good quality algorithms for common tasks.
 Make the results freely available as "libraries" of
subroutines than anyone can use in their programs.
 Libraries are available at: www.netlib.org

CourseIntroduction_10
History
LINPACK, EISPACK.
(1970¶V 
± In the mid-1970s, Cleve
Moler and several colleagues
developed the FORTRAN
subroutine libraries called
LINPACK and EISPACK
under a grant from the
National Science Foundation.
± LINPACK was a collection of
FORTRAN subroutines for
solving linear equations,
while EISPACK contained Jack Dongarra, Cleve Moler, Pete Stewart, and Jim Bunch in 1978
subroutines for solving
eigenvalue problems. C.... factor the A matrix
CALL SGEFA(A, N, N, IPVT, INFO)
± Together, LINPACK and
EISPACK represented state C.... copy B vector into X vector
of the art software for matrix CALL SCOPY(N, B, 1, X, 1)
computation. C.... solve the system of equations
CALL SGESL(A, N, N, IPVT, X, 0)
CourseIntroduction_11

History
 Matlab 0 (1978)
± Cleve Moler designed (as a
"hobby" on his own time ) it to
give his students interactive
EISPACK without having to learn
FORTRAN
± Moler named his program
Matlab, for MATrix LABoratory.
± Over the next several years,
when he would visit another
university to give a talk, or as a
visiting professor, he would end
up by leaving a copy of his
Matlab on the university
machines.
± Within a year or two, Matlab
started to catch on by word of
mouth within the applied math
community as a "cult"
phenomena CourseIntroduction_12
History
 Matlab 1. (1984)
± reprogrammed in C
± commercial potential
=> Mathworks
± 1983, John Little was exposed to
Matlab because of a visit Cleve
± Little, an engineer, recognized
the potential application of
Matlab to engineering
applications.
± Little teamed up with Cleve
Moler and Steve Bangert to
develop a second generation,
professional version of Matlab
written in C and integrated with
graphics.
± The MathWorks, Inc. was
founded in 1984 to market and
continue development of Matlab.
CourseIntroduction_13

History

##  Software has evolved into an interactive system

and programming language for general
scientific and technical computation and
visualization
 The MathWorks has become a commercial
success.
± In the period 1984 ± 1991 the number of employees
has doubled every year, from 2^0 people in 1984 to
2^7 people in 1991.
± In the following years, the staff has increased
roughly 20% per year, from 2^7 people in 1991, to
2^9 people in 1999, and 2^10 people in 2002.
 Matlab 7 (2004)
± Release 14
 Matlab 2009a/b (2009) CourseIntroduction_14
Matlab: pro

##  Ease of use: interpreter and integrated environment

± easy and fast coding
± simple, compact, and procedural language with moderate
learning curve
 Strong graphical and numerical capabilities
 Platform independent
 Predefined functions (toolbox - Spectral Analysis,
Image Processing, Signal Processing, Financial,
Symbolic Math ...)
 Extra functions can be created in M-files.
 Large user base with much user-contributed software
 GUI: user can construct its own gui
 Lots of code and information available on te web

CourseIntroduction_15

Matlab: contra

##  Interpreter can be slow (compiler)

 Few data types/structures supported
 ³+DQGOH*UDSKLFV´IRUFXVWRPL]LQJGLVSOD\
options is difficult to use.
 well written FORTRAN / C code can be faster
 not (yet) suitable for parallel programming
 :HEE :LOVRQ'U'REE¶V-RXUQDO-DQ1999
³/LNHHYHU\RWKHUVFULSWLQJODQJXDJH0DWODE
began as a simple way to do powerful things,
and it has become a not-so-simple way to do
YHU\SRZHUIXOWKLQJV´
 cost CourseIntroduction_16
Why not C, FORTRAN, ...?

##  No built-in graphics; problem to visualize data and

models
 More bookkeeping needed to do things
 pro: Open-source versions exist, some better suited for
specific applications

CourseIntroduction_17

## Spreadsheet programs are very good at dealing with table

data in simple ways, and has graphics built-in
 More advanced calculations require programming in
Visual Basic
 Proprietary, binary file format
 Not available on all platforms

CourseIntroduction_18
CourseIntroduction_19

## Free Matlab Alternatives

 GNU Octave (www.octave.org)
is a high-level language, that is
mostly compatible with Matlab; it
is freely redistributable.

 Scilab (www.scilab.org) is a
scientific software package for
numerical computations
providing a powerful open
computing environment for
engineering and scientific
applications

dictionary:
http://www.scilab.org/product/dic-mat-sci/SCI2M.htm

## Using vs Programming Matlab

 Some problems can be solved using a software tool
(e.g., a spreadsheet program, Excel). It is usually faster
to solve a problem with an existing tool.
 Many problems cannot be solved with such tools, or a
tool is not available. We must then program our own
³WRRO´XVLQJDVXLWDEOHFRPSXWHUODQJXDJH
 Matlab blurs the line between computer tool and
computer language since it is both.

CourseIntroduction_20
References
 Engineering
Computation with
MATLAB
David Smith
Pearson 2008
 Mastering Matlab 7
Duane Hanselman
& Bruce Littlefield
Prentice Hall, 2004

CourseIntroduction_21

References

##  use the mathworks website:

± Matlab getting started
http://www.mathworks.com/access/helpdesk/help/pdf_doc/matl
ab/getstart.pdf
± Matlab reference (3 volumes)
http://www.mathworks.com/access/helpdesk/help/pdf_doc/matl
ab/refbook.pdf
± http://www.mathworks.com/nn_books

CourseIntroduction_23

MATLAB
desktop
Introduction to Matlab

##  Discover how Matlab is designed and what the basic

components do
 Topics
± Matlab Desktop
± HELP
± Basic language syntax

Desktop_2

## Matlab Desktop 7.8

Desktop_6

Current Directory
 Location of the folder that contains scripts that
you have written and any data files you want to
analyze

##  Matlab finds the functions you call by searching the

Matlab Path in the order in which the directories on the
path are specified.
 If multiple functions with the same name exist on the
path, the version associated with the end of the pathlist
is used.
 The easiest way to add new directories or view the
existing path is to use the graphical pathtool available
via file->set path or by typing pathtool at the
command prompt.
Desktop_8

Workspace/Array editor
 Lists variables from
code and experiments
you have run

 double-click the
variable opens a
window showing the
values
 values can be changed
interactively
Desktop_9

Command Window
 main working area
 can run lines of code
 displays values if code
is not concluded with ;
 pushing up arrow
cycles through previous
entries
Desktop_10

Command History
 displays a log of the
statements most
recently run in the
Command Window
 user can copy from this
list one or more lines of
code and paste it into
the command window
 saves history (up to
20k)

Desktop_11

Desktop layout
 Layout can be changed
 Different windows can be shown (or not)
 Windows can be docked/undocked
HELP

 Click on Help-icoon
 helpdesk
Window
Window
 doc + command name: online documentation
 lookfor + search string: search for search string in
Matlab path

Desktop_12

HELP

Desktop_13
HELP
>> help
HELP topics

## matlab\general - General purpose commands.

matlab\ops - Operators and special characters.
matlab\lang - Programming language constructs.
matlab\elmat - Elementary matrices and matrix manipulation.
matlab\elfun - Elementary math functions.
matlab\specfun - Specialized math functions.
matlab\matfun - Matrix functions - numerical linear algebra.
matlab\datafun - Data analysis and Fourier transforms.
matlab\polyfun - Interpolation and polynomials.
matlab\funfun - Function functions and ODE solvers.
matlab\sparfun - Sparse matrices.
matlab\scribe - Annotation and Plot Editing.
matlab\graph2d - Two dimensional graphs.
matlab\graph3d - Three dimensional graphs.
matlab\specgraph - Specialized graphs.
matlab\graphics - Handle Graphics.
matlab\uitools - Graphical user interface tools.
matlab\strfun - Character strings.
matlab\imagesci - Image and scientific data input/output.
matlab\iofun - File input and output.
matlab\audiovideo - Audio and Video support.
matlab\timefun - Time and dates.
matlab\datatypes - Data types and structures.
matlab\verctrl - Version control.
matlab\codetools - Commands for creating and debugging code.
matlab\helptools - Help commands.
Desktop_14
matlab\winfun - Windows Operating System Interface Files (COM/DDE)
matlab\demos - Examples and demonstrations.

##  Matlab is an interpreted language

± Commands are typed into the COMMAND Window
and executed immediately
± Variables are allocated in memory as soon as they
are first used in an expression
± Commands must be re-entered to be re-executed
 All variables created in the Command Window
are in what is called the Base Workspace
± Variables can be reassigned new values as needed
± Variables can be selectively cleared from the
workspace
Desktop_15
Commands, Statements & Variables
At the prompt in the Command Window, you can enter either
a:
± Command:
save mydata (saves workspace in mydata.mat)
whos (displays list of workspace variables)
± Assignment Statement:
A = width * length;
B = 267;
 Assignment statements can have only a single variable on the left
side of the assignment operator (=)
 The RHS is evaluated using current values for all variables and
the resulting value is assigned to the variable on the LHS.
 Values can be numbers or characters
 7KHYDULDEOH¶V7<3(LVDOZD\VXSGDWHGZKHQHYHUDQHZ
PLVWDNHV«
± Variables
 up to 63 characters (more are ignored); Case Sensitive
Desktop_17
 Check with namelengthmax

Editing keys

Key Function
Browse backward through the
commands
Browse forward through the
commands
Scroll backward through a
single command
Scroll forward through a
single command
ctrl Scroll backward through a
single command by word
ctrl Scroll forward through a
single command by word
command line
command line
esc Clear line
backspace Discard character in front of
the cursor
tab Complete a command (select
from the list)

Desktop_18
Variables and Names

##  A variable is a placeholder in memory

 Variables contain values
 Variable names:
± Are case sensitive: Cost, cost, COST are
different
± May contain up to 63 characters (more are ignored)
± May contain numbers and letters
± 0D\127FRQWDLQSXQFWXDWLRQH[FHSW³B´
 How do I view the contents of a variable?
± -XVWW\SHWKHYDULDEOHQDPHZLWKRXWDIROORZLQJ³´

Desktop_19

Reserved Words
 Matlab has some special (reserved) words that you may
QRW UH XVH«
 Use the iskeyword to list all reserved words.

for switch
end continue
if else
while try
function catch
return global
elsif persistent
case break
Desktop_20
otherwise
Case Sensitivity

##  Matlab is case sensitive

 File names
± Matlab running on Windows now gives preference to an exact
(case sensitive) name match, but falls back to an inexact (case
insensitive) match when no exact match can be found.
± Whenever Matlab 7 detects a potential naming conflict related
to case sensitivity, it issues a warning.

Desktop_21

Matlab as a calculator

##  Always see what is being calculated

 Can use variables
 %\SXVKLQJDQXSĹDQGGRZQĻDUURZVFDQFDOO
previously executed commands
 By typing the beginning of command and then using up
arrow can recall commands that start from the typed
symbols
 Can copy and paste into documents
 Can easily plot graphs

Desktop_22
Built-in functions

##  Matlab offers a wealth of built-in math functions

that can be quite helpful for many
computational problems

##  Elementary Matlab functions (help elfun)

± Trigonometric functions
± Exponential functions
± Complex functions
± Rounding and remainder functions

##  Specialized Matlab functions (help specfun)

± Specialized math functions
± Number theoretic functions
± Coordinate transformations
Desktop_23

## Elementary math functions

Trigonometric.
 sin - Sine.
 sind - Sine of argument in degrees.  sec - Secant.
 sinh - Hyperbolic sine.  secd - Secant of argument in degrees.
 asin - Inverse sine.  sech - Hyperbolic secant.
 asind - Inverse sine, result in degrees.  asec - Inverse secant.
 asinh - Inverse hyperbolic sine.  asecd - Inverse secant, result in degrees.
 asech - Inverse hyperbolic secant.
 cos - Cosine.
 csc - Cosecant.
 cosd - Cosine of argument in degrees.  cscd - Cosecant of argument in degrees.
 cosh - Hyperbolic cosine.  csch - Hyperbolic cosecant.
 acos - Inverse cosine.  acsc - Inverse cosecant.
 acosd - Inverse cosine, result in degrees.  acscd - Inverse cosecant, result in degrees.
 acosh - Inverse hyperbolic cosine.  acsch - Inverse hyperbolic cosecant.
 cot - Cotangent.
 tan - Tangent.
 cotd - Cotangent of argument in degrees.
 tand - Tangent of argument in degrees.  coth - Hyperbolic cotangent.
 tanh - Hyperbolic tangent.  acot - Inverse cotangent.
 atan - Inverse tangent.  acotd - Inverse cotangent, result in degrees.
 atand - Inverse tangent, result in degrees.  acoth - Inverse hyperbolic cotangent.
 atan2 - Four quadrant inverse tangent.
 atanh - Inverse hyperbolic tangent.

Desktop_24
Elementary math functions
Exponential. Complex.
 exp - Exponential.  abs - Absolute value.
 expm1 - Compute exp(x)-1 accurately.  angle - Phase angle.
 complex - Construct complex data from real
 log - Natural logarithm. and imaginary parts.
 log1p - Compute log(1+x) accurately.  conj - Complex conjugate.
 log10 - Common (base 10) logarithm.  imag - Complex imaginary part.
 log2 - Base 2 logarithm and dissect  real - Complex real part.
floating point number.  unwrap - Unwrap phase angle.
 pow2 - Base 2 power and scale  isreal - True for real array.
floating point number.  cplxpair - Sort numbers into complex conjugate
pairs.
 realpow - Power that will error out on 
complex
Rounding and remainder.
result.
 fix - Round towards zero.
 reallog - Natural logarithm of real  floor - Round towards minus infinity.
number.  ceil - Round towards plus infinity.
 realsqrt - Square root of number greater  round - Round towards nearest integer.
than or equal to zero.  mod - Modulus (signed remainder after
 sqrt - Square root. division).
 nthroot - Real n-th root of real numbers.  rem - Remainder after division.
 nextpow2 - Next higher power of 2.  sign - Signum.

Desktop_25

## Specialized math functions

Specialized math functions. Number theoretic functions.
 airy - Airy functions.  factor - Prime factors.
 besselj - Bessel function of the first kind.  isprime - True for prime numbers.
 bessely - Bessel function of the second kind.  primes - Generate list of prime numbers.
 besselh - Bessel functions of the third kind  gcd - Greatest common divisor.
(Hankel function).  lcm - Least common multiple.
 besseli - Modified Bessel function of the first  rat - Rational approximation.
kind.
 rats - Rational output.
 besselk - Modified Bessel function of the
second kind.  perms - All possible permutations.
 beta - Beta function.  nchoosek - All combinations of N elements
taken K at a time.
 betainc - Incomplete beta function.
 factorial - Factorial function.
 betaln - Logarithm of beta function.
 ellipj - Jacobi elliptic functions.
Coordinate transforms.
 ellipke - Complete elliptic integral.
 cart2sph - Transform Cartesian to spherical
 erf - Error function. coordinates.
 erfc - Complementary error function.  cart2pol - Transform Cartesian to polar
 erfcx - Scaled complementary error function. coordinates.
 erfinv - Inverse error function.  pol2cart - Transform polar to Cartesian
 expint - Exponential integral function. coordinates.
 gamma - Gamma function.  sph2cart - Transform spherical to Cartesian
 gammainc - Incomplete gamma function. coordinates.
 gammaln - Logarithm of gamma function.  hsv2rgb - Convert hue-saturation-value colors
to red- green-blue.
 psi - Psi (polygamma) function.
 rgb2hsv - Convert red-green-blue colors to
 legendre - Associated Legendre function. hue- saturation-
 cross - Vector cross product. value.
 dot - Vector dot product.

Desktop_26
Some Special Variables

##  ans : default variable name for results

 beep: make sound
 pi: pi
 eps: smallest number that can be subtracted from 0 to
make a negative number
 inf: infinity (or Inf)
 NaN: not a number (or nan)
 realmin: smallest positive real number
 realmax: largest positive real number

Desktop_27

Format

## Format controls display of output in the command window

format short
format long
format rat
format hex

Desktop_28
Matlab Programs

 &DQZHH[HFXWHD³SURJUDP"´RULVLWDVLPSOHFDOFXODWRU"
 Programs in Matlab are:
± Scripts: Matlab statements that are fed from a file into the
Command Window and executed immediately
± Functions: Program modules that are passed data (arguments)
and return a result (i.e., sin(x))
± These can be created in any text editor (but Matlab supplies a nice
built-in editor)

Desktop_29

Editor

commands

Color keyed
text with auto
indents

## tabbed sheets for other

files being edited

Desktop_30
Summary

 desktop environment
 try to use help as much as possible
 besides Matlab Help there is also google
 use Matlab interactively as a calculator

Desktop_31

MATLAB
numeric data types
Basic Data Structure
 array:
± most basic data structure in Matlab
± a two-dimensional, rectangularly shaped data
structure
± can contain numbers, characters, logical states
 Matlab uses these two-dimensional arrays to
store single numbers and linear series of
numbers as well. In these cases, the
dimensions are 1-by-1 and 1-by-n respectively,
where n is the length of the numeric series.
 Matlab also supports data structures that have
more than two dimensions.

data types

##  Matlab is different from C and other common languages

in some important ways:
± basic data structure in Matlab is array.
± variables do not have to be declared beforehand.
overview

## double single int8, unit8 logical char

int16, uint16
int32, unit32
double precision single precision int64, unint64 logical data character strings
(real and complex) (real and complex)
integer and unsigned
integer data types

user function
cell structure
classes handles

## cell arrays structures objects function handles

overview
Numeric Data Types

##  Numeric data types in Matlab include:

± signed and unsigned integers,
± single- and double-precision floating-point numbers.
± Integer and single- precision arrays offer more memory efficient
storage than double precision.
 All numeric types support basic array operations, such
as subscripting and reshaping.
± All numeric types except for int64 and uint64 can be used in
mathematical operations.

integer
 4 signed and 4 unsigned integer data types.
 Signed types:
± enable negative integers as well as positive,
± represent smaller range of numbers as the unsigned types
 Unsigned types
± wider range of numbers
± zero or positive.
 Matlab supports 1-, 2-, 4-, and 8-byte storage for integer
data.
± save memory and execution time for your programs if you use
the smallest integer type that accommodates your data.
± no need for a 32-bit integer to store the value 100.
integer

integer

## Creating Integer Data

 Matlab stores numeric data as double-precision
floating point by default.
 Store data as an integer: use one of the
conversion functions
x = int16(32501);
 Use the whos function to show the dimensions,
byte count, and data type of an array
represented by a variable.
 ex. ± PAY ATTENTION!
x=int8(60);
y=int8(70);
z=x+y;
 ex. demo_integer
floating point: double
 Matlab represents floating-point numbers in:
± double-precision (default)
± single-precision format.
 single precision with a conversion function (single)
 according to IEEE Standard 754 for double precision.
64 bits, formatted as:
Bits Usage
63 sign (0 = positive, 1 = negative)
62 to 52 Exponent, biased by 1023
51 to 0 Fraction f of the number 1.f
 Maximum and Minimum Double-Precision Values:
± realmax and realmin return the maximum and
minimum values that you can represent with the
double data type
± conversion function: double
 ex. demo_float

##  Matlab constructs the single data type

according to IEEE Standard 754 for single
precision. Any value stored as a single requires
32 bits:
Bits Usage
31 sign (0 = positive, 1 = negative)
30 to 23 Exponent, biased by 127
22 to 0 Fraction f of the number 1.f

##  Maximum and Minimum Double-Precision

Values:
± UHDOPD[ µVLQJOH¶ and UHDOPLQ µVLQJOH¶ return the
maximum and minimum values that you can represent with the
double data type
± conversion function: single
complex

##  Complex numbers consist of two separate parts: a real

part and an imaginary part.
 The basic imaginary unit is equal to the square root of -
1.
represented by: i or j
x = 2 + 3i;
 Another way ± use the complex function.
x = rand(3) * 5;
y = rand(3) * -8;
z = complex(x, y)
 Separate a complex number into its real and imaginary
parts using the real and imag functions:
zr = real(z);
zi = imag(z);

## Infinity and NaN

 Infinity x = 1/0
± special value inf. x =
± results from operations like Inf
division by zero and overflow. x = 1.e1000
± Use the isinf function to x =
verify that x is positive or Inf
negative infinity: x = exp(1000)
 NaN x =
± values that are not real or Inf
complex numbers x = log(0)
± NaN: Not a Number. x =
± 0/0 and inf/inf result in NaN -Inf
± Use the isnan function to
verify that x is NaN: x = log(0); isinf(x)
± Logical Operations on NaN. ans = 1
Because two NaNs are not
equal to each other, logical
operations involving NaN x = 7i/0
always return false, except for x = NaN + Infi
a test for inequality
x = log(0); isnan(x) ans = 1
MATLAB
arrays: creation

ArraysCreation_2

Topics

 Creating
± how to build an array in a fast way
± manual entering the elements
± :
± linspace, logspace
± special functions, special matrices
 Indexing
± How to select elements
Help

Search for
 Creating and Concatenating Matrices
 Matrices and Arrays
 Matrix Indexing
 Elementary matrices

ArraysCreation_4

Matlab Arrays

##  0DWODE¶V fundamental data structure is the array

Matlab considers each variable to be a matrix and
"knows" how big it is.
 )XQGDPHQWDORSHUDWRUV HJDGGLWLRQPXOWLSOLFDWLRQ« 
are programmed to deal with matrices when required.
The Matlab environment handles much of the
bothersome housekeeping that makes all this possible.
Basic Concepts
Scalars: magnitude only
x, mass, color, 13.451

Vectors: magnitude
r ANDr direction
force 12.74 i 5.234 j
r r r r r r
H a1i1 a2i2 a3i3 a4i4 L anin

## Arrays: can be 2D or higher dimension

a11 a12 a13 a14
A a21 a22 a23 a24
a31 a32 a33 a34
R rijk
ArraysCreation_5

Creating Arrays

 Different ways:
± specify each element explicitly,
± use the colon : operator,
± use the commands linspace or
logspace
± elementary (built-in) arrays
 The Matlab arrays are indexed as:
A(row,column)

ArraysCreation_6
Creating Arrays

##  Create an array: use the square brackets [ ]

 Specify each element explicitly
 Numbers (or variables) inside the brackets can be
separated by blanks, commas or semicolons
± blank or comma separator: separate elements in a row
± semicolon: separate rows
» a = [1 2 3]
a =
1 2 3
» b = [11, 2, 3]
b =

11 2 3
» c = [1;2;3]
c =
1
2
3

ArraysCreation_7

Creating Arrays

##  always refer to rows first and columns second. 4-by-3

>> A = [1 3 5 ; 2 4 1 ; 3 3 3 ; 2 1 9]
A =
1 3 5
2 4 1
3 3 3
2 1 9
 create an empty matrix.
>> D = []
D =
[]
Creating Arrays: Colon Operator

##  Create vectors, array subscripting, and for

iterations
 The colon (:) is one of the most useful operators
in Matlab.
from_, to _, in increments of_
 The colon operator uses the following rules to
create regularly spaced vectors:
± j:k is the same as [j,j+1,...,k]
± j:k is empty if j > k
± j:i:k is the same as [j,j+i,j+2i, ...,k]
± j:i:k is empty if i > 0 and j > k or if i < 0 and j < k
ArraysCreation_9

Example
» D = 1:4 » d(:)
D = ans =
1 2 3 4 1
» E = 1:0.3:2 11
E = 1
1.0000 1.3000 2
1.6000 1.9000 2
» d 2
d = 3
1 2 3 3
11 2 3 3
1 2 3 » d(2:3)
» d(2,:) ans =
ans = 11 1
11 2 3 » d(8:9)
» d(:,1) ans =
ans = 3 3
1 » d(end:-1:6)
11 ans =
ArraysCreation_10
1 3 3 3 2
Creating Arrays

 linspace
± syntax: x = linspace(first, last, n)
± creates linearly spaced row vector starting with first, ending at
last , having n elements

 logspace
± syntax: x = linspace(first, last, n)
± creates logarithmically spaced row vector starting with 10first,
ending at 10last , having n elements

ArraysCreation_11

Creating Arrays

## Matlab provides functions for creating standard

arrays.
>> help elmat
Elementary matrices and matrix manipulation.

Elementary matrices.
zeros - Zeros array.
ones - Ones array.
eye - Identity matrix.
repmat - Replicate and tile array.
rand - Uniformly distributed random numbers.
randn - Normally distributed random numbers.
linspace - Linearly spaced vector.
logspace - Logarithmically spaced vector.
freqspace - Frequency spacing for frequency response.
meshgrid - X and Y arrays for 3-D plots.
accumarray - Construct an array with accumulation.
: - Regularly spaced vector and index into matrix .

ArraysCreation_12
Examples
>> ones(3) >> randn(3,2)
ans =
ans = -0.4326 0.2877
-1.6656 -1.1465
1 1 1 0.1253 1.1909
1 1 1 >> a=1:4
1 1 1 a =

>> zeros(2,5) 1 2 3 4
>> diag(a)
ans = ans =

0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 2 0 0
0 0 3 0
>> eye(3) 0 0 0 4

## ans = >> diag(a,-2)

ans =
1 0 0
0 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0
1 0 0 0 0 0
>> rand(1,5) 0 2 0 0 0 0
0 0 3 0 0 0
ans = 0 0 0 4 0 0

## 0.9501 0.2311 0.6068 0.4860

0.8913
ArraysCreation_13

Size of a Matrix

##  determine the size of a matrix by using the size()

command
>> A = rand(3)
A =
0.8147 0.9134 0.2785
0.9058 0.6324 0.5469
0.1270 0.0975 0.9575
>> size(A)
ans =
3 3
>> [nrows,ncols] = size(A)
nrows =
3
ncols =
3
Number of Elements

 numel() command.
>> n = numel(A)

n =

9
 length() command (vector)
± the statement length(X) is equivalent to max(size(X))
>> length(A)

ans =

Transposing a Matrix

##  A m-by-n matrix can be transposed into a n-by-m matrix

by using the transpose operator '.
>> A = [1 2 3 4 ; 5 6 7 9]
A =
1 2 3 4
5 6 7 9
!!% \$µ
B =
1 5
2 6
3 7
4 9
Concatenating Matrices

##  Matrices can be concatenated by enclosing them inside

of square brackets and using either a space or
semicolon to specify the dimension.
 Care must be taken that the matrices are of the right
size.
>> A = [[1 2 3],rand(1,3)]
A =
1.0000 2.0000 3.0000 0.9649 0.1576
0.9706
>> B = [A;A]
B =
1.0000 2.0000 3.0000 0.9649 0.1576
0.9706
1.0000 2.0000 3.0000 0.9649 0.1576
0.9706

Repeating Arrays

 reshape
syntax: B = reshape(A,m,n)
returns the m-by-n matrix B whose elements are taken
columnwise from A. An error results if A does not have
m*n elements.

 repmat
syntax B = repmat(A,m,n)
creates a large matrix B consisting of an m-by-n tiling of
copies of A.
repmat(A,n) creates an n-by-n tiling.

ArraysCreation_18
Reshaping
 reshape >> x = 1:9
B = reshape(A,m,n)
returns the m-by-n matrix B
whose elements are taken x =
columnwise from A. An error
results if A does not have m*n 1 2 3 4
elements. 5 6 7 8
 9

>> reshape(x,3,3)

ans =

1 4 7
2 5 8
3 6 9

More functions
Function Description
[a,b] or Create a matrix from specified elements, or concatenate matrices together.
[a;b]
accumarray Construct a matrix using accumulation.
blkdiag Construct a block diagonal matrix.
cat Concatenate matrices along the specified dimension.
diag Create a diagonal matrix from a vector.
horzcat Concatenate matrices horizontally.
magic Create a square matrix with rows, columns, and diagonals that add up to the same
number.
ones Create a matrix of all ones.
rand Create a matrix of uniformly distributed random numbers.
repmat Create a new matrix by replicating or tiling another.
vertcat Concatenate two or more matrices vertically.
zeros Create a matrix of all zeros.
ArraysCreation_20
Concatenate

cat
 Concatenate arrays
 Syntax
± C = cat(dim,A,B)
± C = cat(dim,A1,A2,A3,A4...)
 C = cat(dim,A,B) concatenates the arrays
A and B along dim.
 C = cat(dim,A1,A2,A3,A4,...)
concatenates all the input arrays (A1, A2, A3,
A4, and so on) along dim.
 cat(2,A,B) is the same as [A,B]
 cat(1,A,B) is the same as [A;B]

Indexing

##  Extract individual entries by specifying the indices

inside round brackets ().
 extract several entries at once by specifying
± a matrix,
± use the : operator to extract all entries along a certain
dimension.
Indexing: example
A = rand(5)
A =
0.9572 0.9157 0.8491 0.3922 0.2769
0.4854 0.7922 0.9340 0.6555 0.0462
0.8003 0.9595 0.6787 0.1712 0.0971
0.1419 0.6557 0.7577 0.7060 0.8235
0.4218 0.0357 0.7431 0.0318 0.6948
>> A1=A(3,5)
A1 =
0.0971
>> A2 = A([1, 3], 5)
A2 =
0.2769
0.0971
>> A3 = A(:,1)
A3 =
0.9572
0.4854
0.8003
0.1419
0.4218

Assignment of elements

##  Assignment operations follows the same rules as

indexing and then specify the new values on the right
hand side.
 The right must be either a scalar value, or a matrix with
the same dimensions as the resulting indexed matrix on
the left.
 Matlab automatically expands scalar values on the right
to the correct size
>> A = ones(3,5)
A =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
>> A(3,2) = 5
A =
1 1 1 1 1
1 1 1 1 1
1 5 1 1 1
>> A(:,1:3:end) = 8
A =
8 1 1 8 1
8 1 1 8 1
8 5 1 8 1

Deletion

##  Assigning [] deletes the corresponding entries from the

matrix.
 Only deletions that result in a rectangular matrix are
allowed.
A =
8 1 1 8 1
8 1 1 8 1
8 5 1 8 1
>> A(2,1)=[]
??? Subscripted assignment dimension mismatch.
>> A(2,:)=[]
A =
8 1 1 8 1
8 5 1 8 1
Expansion

##  When the indices in an assignment operation exceed

the size of the matrix, the matrix will be expanded
 No error message!
 Be careful!
>> A = magic(3)
A =
8 1 6
3 5 7
4 9 2
>> A(5,7) = 99
A =
8 1 6 0 0 0 0
3 5 7 0 0 0 0
4 9 2 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 99

Summary

##  manual entering the elements

 :
 linspace, logspace
 special functions, special matrices

 ex.: demo_array_creation

ArraysCreation_28
MATLAB
array operations

Topics

 Mathematical operations
 Manipulation
 Sorting and searching
 More built-in manipulation
 Multidimensional arrays

ArraysOperations_2
Help

Search for
 Arithmetic operators
 Array operators

## Basic Matrix Operations

ArraysOperations_4
Dot (Array) Operations

ArraysOperations_5

Scalar-Array Mathematics
 Addition, >> g = [1 2 3 4; 5 6 7 8]

subtraction, g =

1 2 3 4
multiplication, and 5 6 7 8

3
0
4
1
5
2
6

array. ans =

1 3 5 7
9 11 13 15

>> 3*g/5+4

ans =

## 4.6000 5.2000 5.8000 6.4000

7.0000 7.6000 8.2000 8.8000

ArraysOperations_6
Array-Array Mathematics

##  Mathematical operations between arrays are not so

simple as those between scalars and arrays
where cij = aij+bij
± Multiplication/division: C=A .* B
where cij = aij*bij
± Exponentiation:
C=A .^ x
where cij = aijx
 Same order of precedence rules as under basic scalar
operations

ArraysOperations_7

Array-Array Mathematics

##  Arithmetic operations on arrays are just like the same

operations for scalars but they are carried out on an
element-by-element basis.
± the dot (.) before the operator indicates an array operator; it is
needed only if the meaning cannot be automatically inferred.
± when combining arrays, make sure they all have the same
dimensions
± applies to vectors, 2D arrays, multi-dimensional arrays

ArraysOperations_8
Example
>> g >> g + h

g = ans =

1 2 3 4 2 3 4 5
5 6 7 8 7 8 9 10
9 10 11 12 12 13 14 15

## >> h >> 2*g-h

h = ans =

1 1 1 1 1 3 5 7
2 2 2 2 8 10 12 14
3 3 3 3 15 17 19 21

>>
ArraysOperations_9

Example
>> g*h » g * h'
??? Error using ==> mtimes
Inner matrix dimensions ans =
must agree.
10 20 30
26 52 78
>> g.*h 42 84 126
» g' * h
ans =
ans =
1 2 3 4
10 12 14 16 38 38 38 38
27 30 33 36 44 44 44 44
50 50 50 50
56 56 56 56

ArraysOperations_10
More on Array Operations
 Most Matlab functions will >> A=[1 2 3 4 5];
work equally well with >> sin(A)
ans =
both scalars and arrays
0.8415 0.9093
(of any dimension) 0.1411 -0.7568
-0.9589
>> sqrt(A)
ans =
1.0000 1.4142
1.7321 2.0000
2.2361

ArraysOperations_11

## >> A = [1:3;4:6;7:9] Most common functions

A = operate on columns by
1 2 3 default
4 5 6
7 8 9

>> mean(A)
ans =
4 5 6

>> sum(A)
ans =
12 15 18
ArraysOperations_12
Reversing
 reversing rows and >> a = [1 2 3 ; 4 5 6 ; 7 8 9]
columns a =

1 2 3
4 5 6
7 8 9

>> b = a(end:-1:1)

b =

9 6 3 8 5
2 7 4 1

>> b = a(end:-1:1,1:3)

b =

7 8 9
4 5 6
ArraysOperations_13 1 2 3

Sorting
 Sort array elements in >> a = randperm(8)
ascending or descending a =
8 2 7 4 3 6
order 5 1
 Syntax >> b = sort(a)
b =
± B = sort(A) 1 2 3 4 5 6
7 8
± B = sort(A,dim) >> A
± B = sort(...,mode) A =
± [B,IX] = sort(...) 3 7 5
0 4 2
 B = sort(A) sorts the >> sort(A)
elements along different ans =
0 4 2
dimensions of an array, and 3 7 5
arranges those elements in >> sort(A,1)
ans =
ascending order.
 If A is a ...sort(A) ... 0 4 2
3 7 5
± Vector: Sorts the elements of >> sort(A,2)
A. ans =
± Matrix: Sorts each column of 3 5 7
0 2 4
A.
ArraysOperations_14
Sorting
a =
 B = sort(A,dim) sorts
the elements along the 6
7
4
8
1
2
5
3
dimension of A specified
by a scalar dim. If dim is >> [xs indx] = sort(a,
a vector, sort works 'descend')
iteratively on the
specified dimensions. xs =
Thus, sort(A,[1 2]) is
equivalent to 8 7 6 5
sort(sort(A,2),1). 4 3 2 1

 B = sort(...,mode)
sorts the elements in the indx =
specified direction,
depending on the value 2 1 5 8
of mode. 6 4 3 7
±
DVFHQGµ Ascending order
(default)
ArraysOperations_15
±
GHVFHQGµDescending order

Searching
 The find FRPPDQG³ILQGV´ >> grades = -5: 10: 105
members of an array that -5 5 15 25 35
meet a criteria. The 45 55 65 75 85
result of the command is 95 105
a list of element numbers. grades <0)
set1 =
1 12
set2 =
2 3 4 5 6
7 8 9 10 11
ans =
-5 105
ans =
5 15 25 35 45
55 65 75 85 95

ArraysOperations_16
Searching
 The find FRPPDQG³ILQGV´ >> a = 1:9
works also in 2 dimensions a =
1 2 3 4 5 6
 more specific 7 8 9
>> a = reshape(a,3,3)'
 find(X, n): a =
1 2 3
start at the first element 4
7
5
8
6
9
returns up to n indices where >> [ii,ij]=find(a>5)
X is true ii =
3
 ILQG ;Q¶ODVW¶  3
2
start at the last element 3
returns up to n indices where ij =
1
X is true 2
3
3
>> k = find(a>5)
k =
3
6
8
9
>> l = find(a>5, 2, 'last')
l =
ArraysOperations_17 8
9

Built-in functions
help elmat: Matrix manipulation. a =
1 2 3
 fliplr: Flip matrix in left/right 4 5 6
7 8 9
direction. >> flipud(a)
 flipud: Flip matrix in up/down ans =
7 8 9
direction. 4 5 6
 rot90: Rotate matrix 90 degrees. 1 2 3
>> fliplr(a)
rot90(a,n): Rotate n-times ans =
 circshift(A,shiftsize) 3 2 1
6 5 4
circularly shifts the values in the array, 9 8 7
A, by shiftsize elements. >> rot90(a)
± shiftsize is a vector of integer scalars ans =
3 6 9
where the n-th element specifies the 2 5 8
shift amount for the n-th dimension of 1 4 7
array A. >> rot90(a,2)
ans =
± positive shiftsize: shift down (or to the 9 8 7
right). 6 5 4
± negative shiftsize: shift up (or to the 3 2 1
>> circshift(a,[-1 1])
left). ans =
± 0: no shift 6 4 5
9 7 8
ArraysOperations_18 3 1 2
Built-in functions
 diag - Diagonal a =
1 2 3
matrices and diagonals of 4 5 6
7 8 9
matrix. >> diag(a)

##  tril - Extract lower ans =

1
triangular part. 5
9
 triu - Extract upper >> diag(ans)
ans =
triangular part. 1 0 0
0 5 0
0 0 9
>> triu(a)
ans =
1 2 3
0 5 6
0 0 9
>> tril(a)
ans =
1 0 0
4 5 0
7 8 9

ArraysOperations_19

Multidimensional Arrays

##  arrays with more than 2 subscripts

 Examples:
± 3D physical data
± sequence of matrices
± samples of a time-dependent 2D or 3D data
 To make multidimensional array:
>> a = [2 4 6; 7 8 9; 1 2 3]
>> a(:,:,2)= [1 11 12; 0 1 2; 4 5 6]
When you add elements and expand the size
Unspecified elements are set to zero
>> a(:,:,4) = [ 1 1 1; 2 2 2; 3 3 3]
Summary

##  mathematics: matrix versus arrays

 sorting and searching functions
 multidimensional arrays

ArraysOperations_21

## Functions & Arrays

ArraysOperations_22
Functions & Arrays

ArraysOperations_23

## Functions & Arrays

ArraysOperations_24
Functions on matrix

ArraysOperations_25

MATLAB
relational and logical
operators
Topics

##  Use relational operators to test two

values
 Work with values of true and false
 Compare relationships using logical
operators
 Analyze the precedence of
operators

LogicalRelational_2

Help

Search for
 Logical operator
 Relational operator
Logical Expressions

Why?
 What if you want to choose between two (or more)
possible programming paths?
 Use a logical condition to decide what to do next
 Requires logical operators

LogicalRelational_4

##  Contains numeric data.

 Arithmetic operators:
± +, - , *, .*, / , ./, ^, .^
 Rules of precedence for arithmetic operators:
± 1. Parentheses
± 2. Exponents
± 3. Multiplication / Division
 combine arithmetic operators with parentheses as
QHHGHGWRFUHDWHPRUHFRPSOLFDWHGH[SUHVVLRQV«

LogicalRelational_5
Relational Operators
 Used to compare two
Relational Operators:
numeric values < less than
 Returns a value of true <= less than or equal to
or false. > greater than
 In Matlab, >= greater than or equal to
== equals to
± 1 = true (any non-zero
number); ~ = not equal to
± 0 = false;
± Logical data type

LogicalRelational_6

Operator Precedence
1. Parentheses ()
2. Transpose (.'), power (.^), complex conjugate transpose ('), matrix
power (^)
3. Unary plus (+), unary minus (-), logical negation (~)
4. Multiplication (.*), right division (./), left division (.\), matrix
multiplication (*), matrix right division (/), matrix left division (\)
6. Colon operator (:)
7. Less than (<), less than or equal to (<=), greater than (>), greater
than or equal to (>=), equal to (==), not equal to (~=)
8. Element-wise AND (&)
9. Element-wise OR (|)
10. Short-circuit AND (&&)
11. Short-circuit OR (||)
Operator Precedence

##  When relational operators are present:

± All arithmetic operations are performed first (in their
particular order)
± Then the relational operators are evaluated.
 Example 1
(2*3) > (4+1);
- The multiplication and addition are first:
6 > 5
- The relational operator is evaluated:
6 is greater than 5, so this returns 1 (true)
- Result is the numeric value, 1, is returned

LogicalRelational_8

##  The Matlab relational operators compare

corresponding elements of arrays with equal
dimensions.
 Relational operators always operate element-
by-element.
 example
A = [2 7 6;9 0 5;3 0.5 6];
B = [8 7 0;3 2 5;4 -1 7];
A == B
ans =
0 1 0
0 0 1
0 0 0
Relational Operators

##  vectors and rectangular arrays, both operands must be

the same size unless one is a scalar.
 one operand is a scalar and the other is not, Matlab
tests the scalar against every element of the other
operand.
 result:
± relation is true receive logical 1
± relation is false receive logical 0.
± on array manipulations: result is a logical array

LogicalRelational_10

Logical Operators
 Logical Operators:
± Provide a way to combine results
from Relational Expressions or Logical Operators
between logical values
± Returns a value of true or false. & AND
 Evaluated after all other | OR
operators have been
performed. ~ NOT
xor XOR

LogicalRelational_11
Logical Operators

 AND: &
± Returns true if two expressions being compared are true.
± Returns false if any of the two is false.
 OR: |
± Returns true if any of the two expressions is true.
± Returns false only if the two are both false.
 NOT: ~
± Returns true if the single expression is false.
± Returns false if the single expression is true.

LogicalRelational_12

Examples:
 Assume: a=7; b=4; c=3;
 ~(a==3*b)
± Evaluates: 3*b = 12
± Evaluates: (a==12) and result is false
± Evaluates ~(false) and result is true
± Returns ans = 1 (true)
 a > 5 & b > 5
± Evaluates (a>5) and (b>5) separately.
± One returns true, the other returns false.
± Since both are not true, the expression returns false.
 a == 7 | b ==1
± Evaluates (a==7) and (b==1) separately
± One returns true and the other returns false
± Since at least one is true, the expression returns true
Logical Operators: more

## 3 types of logical operators and functions:

± Element-wise ² operate on corresponding elements of logical
arrays.
± Bit-wise ² operate on corresponding bits of integer values or
arrays.
± Short-circuit ² operate on scalar, logical expressions.
 logical operators work also on arrays

LogicalRelational_14

## Element-Wise Operators and Functions

The following logical operators and functions
perform element-wise logical operations on
their inputs to produce a like-sized output
array.
examples
A = [0 1 1 0 1];
B = [1 1 0 0 1];

LogicalRelational_15
Logical Operators: more

Bit-Wise Functions
 bit-wise logical operations on nonnegative integer
inputs.
 inputs may be scalar or in arrays.
 examples
A = 28;
% binary 11100
B = 21;
% binary 10101

LogicalRelational_16

## Logical Operators: more

Short-Circuit Operators
 The following operators perform AND and OR
operations on logical expressions containing scalar
values.
 They are short-circuit operators in that they evaluate
their second operand only when the result is not fully
determined by the first operand.

LogicalRelational_17
Example

example: logical_ex_1.m
x=5;
y=10;
disp(x <y)
disp(x<=y)
disp(x==y)
disp((x>10) & (y<30))
disp((x>2) | (y > 89))

LogicalRelational_18

A Common Mistake
 You will not get into trouble if you make sure that Logical
Operators are always used with logical values.
 A > B & C (where A=10, B=5, C=0)
± This looks like a relational expression asking if A is greater than
both B and C which should be true for these values.
± Here is what really happens:
 A>B is evaluated as true
 result (true) is logically ANDed with C
 Since Matlab treats any zero numeric as false, it will mistakenly treat C
as a logical and the result will be false
± The CORRECT form is: (A > B) & (A > C)and this returns a
true result.
± NOTE: subtle problems can arise because Matlab uses numerics to
represent logical values. Other languages are stricter in this area
DQGZRQ¶WOHWWKLVKDSSHQ
Logical Values in Assignments
 True/False values can be assigned to variables
DQGWKHQWUHDWHGQXPHULFDOO\LQ0DWODE«
 The variables will be assigned the value that is
returned from relational and/or logical operators.
 The variables will thus have a value of 1 or 0.
Example: a=7; b=4; c=3;
± x = a > 2;
 Then x = 1;
± y = b==5;
 Y will be equal to 0.
 This can be very useful in Matlab but it is actually
quite DANGEROUS

More Examples

## a=6; b=10; c=-2;

Try the following examples without the use of Matlab:
X1 = abs(c)>3 & c<(b-a) & b+a > 3
X2 = (b==10) | (a< 4)
X3 = a.*5 >= b.*3 & c < a
Advice: use parentheses to make expression more

LogicalRelational_21
Practice

##  Evaluate the following:

± a = 4; b = 20; c = 12; d = 5;
± One = a>4 & b==20
± Two = b<40 | c>10
± Three = d.*c > a.*b
± Four = b.*3<= 100 & d<10 & a.*d==b

LogicalRelational_22

More Practice

##  When comparing vectors, the operator (>, <=, ~,

AND, etc.) is applied element-by-element:

a = [0,2,4,2]; b = [4,1,-2,3];
What is:
C = a .* b;
C = b.^2-a.*b
C = a >= b;

##  Advice: be careful when comparing floating point

numbers because the finite precision may cause
values to be slightly off
LogicalRelational_23
An Interesting Example
 Sometimes if you have to do an array division, you may
want to avoid getting inf when a value in the divisor is
]HUR«

>> B=[2:-1:-2]
B = 2 1 0 -1 -2
>> numerator=ones(size(B))
numerator = 1 1 1 1 1
>> numerator./B
Warning: Divide by zero.
ans = 5.0000e-001 1.0000e+000 Inf -1.0000e+000 -5.0000e-001
>> B=B+(B==0)*eps
B = 2.0000e+000 1.0000e+000 2.2204e-016 -1.0000e+000 -2.0000e+000
>> numerator./B
LogicalRelational_24
ans = 5.0000e-001 1.0000e+000 4.5036e+015 -1.0000e+000 -5.0000e-001

6RPH2WKHU:DUQLQJV«
 Using numeric values to represent logicals can have some
VWUDQJHUHSHUFXVVLRQV«
 Never try to use NaN in a relational or logical expression
because NaN has no value and therefore could be
considered to have all values!
aa = [ 10 16 16 16 17 9 11]
>> aa > 15
>> nan==nan
ans = 0 1 1 1 1 0 0 ans =
>> aaa = ans
>> aa(aaa) 0
ans =
16 16 16 17 >> inf==inf
>> aaai = uint16(aaa)
aaai = ans =
0 1 1 1 1 0 0
>> aa(aaai)
1
??? Subscript indices must either be real positive
integers or logicals.
Logical Functions
 Matlab includes a large number of logical functions
(functions that return a true or false result)
 0DQ\RIWKHPRVWXVHIXODUHZKDWDUHFDOOHG³LVD«´
functions
± any( )
± all( )
± find( )

LogicalRelational_26

## ages = [10 62 18 27] allAdults = all(ages >=

anyKids = any(ages <= 12) 18)
anySeniors = any(ages >= noSeniors = all(ages <=
65) 65)

1 0

anySeniors = noSeniors =

0 1

LogicalRelational_27
Summary
 Matlab can store and Relational Operators:
manipulate much more < less than
than simply numbers <= less than or equal to
 logical expressions on > greater than
arrays >= greater than or equal
to
 GRQ¶WIRUJHW == equals to
~ = not equal to
Logical Operators
& AND
| OR
~ NOT
xor XOR

MATLAB
interactive plotting
Topics

##  Create various types of graphs

 Select variables to plot directly from a workspace
browser
 Easily create and manipulate subplots in the figure
 Add annotations such as arrows, lines, and text
 Set properties on graphics objects

GraphicsInteractive_2

GraphicsInteractive_3

 Steps in plotting your
data
 If only previewing or
exploring data, steps 1 Call elementary plotting
function
and 2 may be all you
need. Select line and marker
 If creating presentation Characteristics

## graphics, you may want

Set axis limits, tick
to finetune your graph marks, and grid lines
by positioning it on the marks, and grid lines

## page, setting line styles Annotate the graph

and colors, adding with axis labels, legend
and text
annotations, etc.
interactive plot editing

##  Matlab supports two ways to edit the plots you create:

± Using the mouse to select and edit objects interactively
± Using Matlab functions at the command line or in an M-file
 Interactive mode:
± perform point-and-click editing of graphs
± modify the appearance of a graphics object by double-clicking
on the object and changing the values of its properties
± access the properties through a gui

GraphicsInteractive_4

GraphicsInteractive_6

Plotting Tools
 Start:
± use the plottools
command.
± from the figure toolbar -
Show Plot Tools icon .
 3 basic plotting tools
± Figure Palette,
± Plot Browser,
± Property Editor.
basic plotting tools

##  Figure Palette: create and arrange subplot axes, view

and plot workspace variables, and add annotations.
 Plot Browser:
± select and control the visibility of the axes or graphic objects
plotted in the figure.
± add data to any selected axes by clicking the Add Data button.
 Property Editor: set common properties of the selected
object.

GraphicsInteractive_7

GraphicsInteractive_8

## Figure Palette / subplots

2-D or 3-D axes to the
figure.
± create a grid of either 2-
D or 3-D axes.
± click the grid icon next to
the axes type.
± move the cursor,
squares darken to
indicate the layout of
axes
GraphicsInteractive_9

## Figure Palette / variables

 displays current workspace
variables.
 double-clicking a variable
opens that variable
 select a variable and right-
click to display the context
function to plot the variable.
 If the desired plotting
function is not available
can select More Plots to
display the Plot Catalog
tool.

GraphicsInteractive_10

## Figure Palette / annotations

arrows, rectangles, basic annotations in
ellipses, and other Figure Palette
annotation objects
anywhere on the figure
 Anchor annotations to
locations in data space
colorbar
titles
 Edit the properties of
graphics objects
GraphicsInteractive_11

## Figure Palette / annotations

 Annotation features are
available from the

##  Select Plot Edit

Toolbar from the View
toolbar.

GraphicsInteractive_12

Plot Browser
 provides a legend of all the graphs in the figure. It
lists each axes and the objects (lines, surfaces,
etc.) used to create the graph.
Plot Browser

##  Controlling Object Visibility

check box next to each item in the Plot Browser controls
WKHREMHFW¶VYLVLELOLW\8QFKHFNWKHFROXPQV\RXGRQRW
want to display.
 Deleting Objects
delete any selected item in the Plot Browser by
selecting Delete from the right-click context menu.
mechanism to add data to axes:
± Select a 2-D or 3-D axes from the New Subplots subpanel.
± After creating the axes, select it in the Plot Browser panel to
enable the Add Data button at the bottom of the panel.
± Click the Add Data button to display the Add Data to Axes
dialog.

GraphicsInteractive_13

Property Editor

 HQDEOHV\RXWRDFFHVVDVXEVHWRIWKHVHOHFWHGREMHFW¶V
properties.
 when no object is selected, the Property Editor displays
WKHILJXUH¶VSURSHUWLHV
 Ways to Display the Property Editor
± Double-click an object when plot edit mode is enabled.
± Select an object and right-click to display its context menu, then
select Properties.
± Select Property Editor from the View menu.

GraphicsInteractive_14
Property Editor
 Property Editor
enables you to
change the
most
commonly
used object
 select an
object, the
property editor
changes
accordingly
 to access all
object
properties, use
the Property
Inspector.

GraphicsInteractive_15

##  in a format that can be opened during another

Matlab session
± Select Save from the figure window File menu or click the Save
button on the toolbar. If this is the first time you are saving the
file, the Save As dialog box appears.
± Make sure that the Save as type is Fig-File.
± Specify the name you want assigned to the figure file.
± Click OK.

GraphicsInteractive_16

##  in a format that can be used by other

applications
± Select the format from the list of formats in the Save as type
drop-down menu. This selects the format of the exported file
and adds the standard filename extension given to files of that
type.
± Enter the name you want to give the file, less the extension.
± Click Save.

GraphicsInteractive_17

GraphicsInteractive_18

Generate code
 generate code to reproduce this graph by
selecting Generate M-File from the Figure
Matlab creates a function that recreates the
graph and opens the generated M-File in the
editor.
 This feature is particularly useful for capturing
property settings and other modifications made
using the plot tools GUI.
 Data Arguments
Generated functions do not store the data
necessary to recreate the graph.
You must supply the data arguments
 Limitations
Attempting to generate code for graphs
containing a large number of graphics objects
(e.g., greater than 20 plotted lines) might be
impractical.
MATLAB
basic mathematical
applictions

Topics

##  basic data analysis

± mean,
± standard deviation, ....
 interpolation
 curve fitting
 polynomials
 solving linear equations
 function optimisation

basicMath_2
 Import Wizard for data import
± File-!,PSRUW'DWD«
± B = ORDG µGDWDLQW[W¶
 File output with save
± VDYH µdataout¶µ\$¶µ-ascii¶

## Data Analysis functions

 help datafun
 Search for:
± Data analysis
 Minimum of in a Data Set >> min(v)
 Maximum of in a Data Set >> max(v)
 Sum of a Data Set >> sum(v)
 Standard Deviation >> std(v)
 Mean of a Data Set >> mean(v)
 Sort a Data Set in ascending order>> sort(v)

 remark:
MATLAB considers databasicMath_4
sets stored in column-oriented
arrays
mean
>> temp3city =
>> mean(temp3city, 1)
12 8 18 ans =  vectors: mean(X) is the
15
12
9
5
22
19
11.9677 8.2258
>> mean(temp3city, 2)
19.8710
mean value of the
14
12
8
6
23
22
ans = elements in X.
12.6667
11
15
9
9
19
15 15.3333  matrices, mean(X) is a
8
19
10
7
20
18
12.0000
15.0000
row vector containing the
12
14
7
10
18
19
13.3333
13.0000
mean value of each
11
9
8
7
17
23 13.0000 column.
8
15
8
8
19
18
12.6667
14.6667  mean(X,DIM) takes the
8
10
9
7
20
17
12.3333
14.3333
mean along the
12
9
7
8
22
19 12.0000 dimension DIM of X.
12 8 21 13.0000
12 8 20 11.6667
10 9 17 13.6667
13 12 18
12.3333
9 10 20
10 6 22 11.3333
14 7 21 13.6667
12 5 22 12.0000
13 7 18 13.6667
15 10 23
13.3333
13 11 24
12 12 22 12.0000
14.3333
13.0000 basicMath_5
«

median
 median(x) same as >> X = [0 1 2; 3 4 5]
mean(x), only returns X =
the median value.
0 1 2
3 4 5

>> median(X,1)

ans =

## 1.5000 2.5000 3.5000

>> median(X,2)

ans =

1
4

basicMath_6
std
Standard deviation >> dat =
>> std(dat)
 There are two common textbook 12 8 18 ans =
definitions for the standard deviation s of 15 9 22 2.5098 1.7646
a data vector X. 12 5 19 2.2322
14 8 23 >> std(dat,1)
 Def_1 12 6 22 ans =
1 11 9 19
n 2.4690 1.7360
1 2 2
s xi x 15 9 15
2.1959
n 1i 1 8 10 20
>> std(dat,0,2)
19 7 18
12 7 18 ans =
 Def_2 14 10 19 5.0332
1 11 8 17 6.5064
n
1 2 2 9 7 23
s xi x 7.0000
n i 1
8 8 19
7.5498
15 8 18
 s = std(X) 8 9 20 8.0829
X is a vector, returns the standard 10
12
7
7
17
22
5.2915
deviation using (1) above. X is a matrix, 9 8 19
3.4641
std(X) returns a row vector containing the 12 8 21
6.4291
standard deviation of the elements of 12 8 20 6.6583
10 9 17 5.5076
each column of X. 13 12 18 4.5092
 s = std(X,flag) 9 10 20 4.5826
flag = 0, is the same as std(X). 10
14
6
7
22
21
8.7178
flag = 1, std(X,1) returns the standard 12 5 22 6.3509
deviation using (2) 13 7 18 5.1316
 s = std(X,flag,dim) computes the 15
13
10
11
23
24
6.6583
standard deviations along the dimension 12 12 22
5.1316
7.6376
of X specified by scalar dim. Set flag to 0
4.3589
to normalize Y by n-1; set flag to 1 to ...
basicMath_7
normalize by n

max (min)
>> dat = >> max(dat)
 max Largest component. 12 8 18
ans =
15 9 22
 vectors: MAX(X) is the 12
14
5
8
19
23 19 12 24
largest element in X. 12
11
6
9
22
19
 matrices: MAX(X) is a row 15
8
9
10
15
20
>> max(max(dat))

12
7
7
18
18
ans =

## maximum element from 14

11
10
8
19
17
24

each column. 9
8
7
8
23
19 >> max(dat(:))

##  [Y,I] = max(X) returns 15

8
8
9
18
20 ans =
the indices of the maximum 10
12
7
7
17
22
24
values in vector I. 9
12
8
8
19
21 >> [Y, I] = max(dat)

10
8
9
20
17 Y =

## the same size as X and Y 13

9
12
10
18
20
19 12 24
with the largest elements 10
14
6
7
22
21

## taken from X or Y. Either 12

13
5
7
22
18 I =
one can be a scalar. 15
13
10
11
23
24
9 23 30
 [Y,I] = 12 12 22

max(X,[],DIM) operates
along the dimension DIM.
diff
>> dat = >> Y
 Y = diff(X) calculates Y =
19 12 24
12 8 18
differences between adjacent 15 9 22
>> diff(Y)
ans =
elements of X. 12
14
5
8
19
23
-7 12
>> diff(Y,2)
 vector: returns a vector, 1 12
11
6
9
22
19
ans =
19
element shorter than X, of 15 9 15 >> diff(dat)
ans =
19
10
7
20
18
3 1 4

## elements: [X(2)-X(1) X(3)-X(2) 12 7 18

-3
2
-4
3
-3
4
14 10 19
... X(n)-X(n-1)] 11 8 17
-2
-1
-2
3
-1
-3

##  matrix, then diff(X) returns a 9

8
7
8
23
19 -7
4 0
1
-4
5
matrix of row differences: 15
8
8
9
18
20
11
-7
-3
0
-2
0
[X(2:m,:)-X(1:m-1,:)] 10 7 17
-3
2 3
-2
1
-2
12 7 22
 Y = diff(X,n) applies diff 9 8 19
-2
-1
-1
1
6
-4
recursively n times, 12
12
8
8
21
20 -7
7 0
1
-1
2
diff(X,2) is same as diff(diff(X)). 10 9 17 2 -2 -3
13 12 18 2 0 5
 Y = diff(X,n,dim) is the nth 9 10 20 -3
3
1
0
-3
2
10 6 22
difference function calculated 14 7 21 0 0 -1
-2 1 -3
along the dimension specified 12
13
5
7
22
18
3 3 1
by scalar dim. 15 10 23
-4
1
-2
-4
2
2
If order n equals or exceeds 13
12
11
12
24
22 -2
4 1
-2
-1
1
the length of dimension dim, 1
2
2
3
-4
5
diff returns an empty array. basicMath_9 -2 1 1
-1 1 -2

filter

## filters a data sequence using a digital filter

 y = filter(b,a,X) filters the data in vector X
with the filter described by numerator coefficient
vector b and denominator coefficient vector a.
If X is a matrix, filter operates on the columns of
X.
 Algorithm:
y(n) = b(1)*x(n) + b(2)*x(n-1) + ... + b(nb+1)*x(n-
nb)
- a(2)*y(n-1) - ... - a(na+1)*y(n-na)
 more detail in help filter
filter
>> time_series = [12 17 10 22 15 11 18 27 14]

time_series =

12 17 10 22 15 11 18
27 14

a =

## 0.2500 0.5000 0.2500

>> filter(a,1,time_series)

ans =

Columns 1 through 8

## 3.0000 10.2500 14.0000 14.7500

17.2500 15.7500 13.7500 18.5000

Column 9

21.5000

basicMath_11

more functions

##  corrcoef: correlation coeeficients

 cov: covariance matrix
 cumprod: cumulative product of elements
 cumsum: cumulative sum of elements
 histc(x, edges): histogram count and bin
locations using bins marked by edges
 prod: product of elements
 sort: sorts in ascending or descending order
 sortrows: sort rows in ascending order
 sum: sum of elements
 demo_basic_DataAnalysis
basicMath_12
Fitting/interpolation

Tips:
 Check Cleve 0ROHU¶V website
± www.mathworks.com/moler
 Help
± Search in helpdesk data analysis
± Interpolation
± fitting

BasicDataAnalysis_13

Interpolation

 (VWLPDWHDYDULDEOH¶VYDOXHEHWZHHQNQRZQYDOXHV
± When you take data, how do you predict what other
data points might be?
± Two techniques are :
 Linear Interpolation

 Extrapolation
Interpolation

##  YI = interp1(X,Y,XI) interpolates to find YI, the

values of the underlying function Y at the points in the
vector or array XI
 Finding values between data points
±linear interpolation (default)
±cubic splines
±...
yi = interp1 ( x, y, xi )
Yi = interp1 ( x, y, xi, 'spline' )

±demo_interp1
±demo_interp2
±demo_interp3
BasicDataAnalysis_15

Fitting

##  There is scatter in all collected data

 We can estimate what equation represents the
GDWDE\³H\HEDOOLQJ´DJUDSK
 But there will be points that do not fall on the
line we estimate
 method
± method of least squares
± minimize the residuals

basicMath_16
Linear regression

##  Linear equation that is the best fir to a set of data points

 Minimize the sum of squared distances between the
line and the data points
 demo_linreg1.m

Polynomial Fit

##  polyfit finds the coefficients of a polynomial

representing the data
 JHQHUDWHVD³EHVWILW´SRO\QRPLDO LQWKHOHDVW
squares sense) of a specified order for a given
set of data.
 used to generate the n + 1 coefficients aj of the
nth-degree polynomial used for fitting the data.
pn (x) an xn an 1xn 1 K an x a0
 polyval: uses those coefficients to find new
values of y, that correspond to the known
values of x basicMath_18
polyfit
>> x = [0 .1 .2 .3 .4 .5 .6 .7
.8 .9 1];
>> y = [-.447 1.978 3.28 6.16
7.08 7.34 7.66 9.56 9.48
9.30 11.2];
>> n = 2;
>> p = polyfit(x,y,n);
>> p =
-9.8108 20.1293 -0.0317
xi = linspace(0,1,100);
yi = polyval(p,xi);
pp = polyfit(x,y,10);
y10 = polyval(pp,xi);
plot(x,y,'o',xi,yi,'--
',xi,y10) % plot data
xlabel('x'), ylabel('y=f(x)')
title('2nd and 10th Order
Curve Fitting')
demo_polyfit
basicMath_19

built-in tool

basicMath_20
polynomials
 Polynomials are described by using a row vector of the coefficients of the
polynomial beginning with the highest power of x and inserting zeros for
³PLVVLQJ´WHUPV
f=[9 ±5 3 7];
g=[6 ±1 2];

##  add and subtract polynomial functions in MATLAB. To do this we must

³]HUR´SDGWKHSRO\QRPLDOVVRWKDWWKHLUURZYHFWRUUHSUHVHQWDWLRQVDUHWKH
same length:
h=f+[0 g];

 multiply and divide polynomials by using the conv and deconv functions
y=conv(f,g)
[q r]=deconv(y,f)

p=[1 3 -4];
x=[-5:.1:5];
px=polyval(p,x);
basicMath_21

polynomials

##  roots finds polynomial roots.

roots( [ 1 6 11 6 ] )
ans = -3.0000
-2.0000
-1.0000
 polyder(P) returns the derivative of the
polynomial whose coefficients are the elements
of vector P.
>> polyder( [ 1 6 11 6 ] )
ans = [ 3 12 11 ]
Solution?

2x1 3x2 8
5x1 4x2 13
A = [2 3; 5 4]
b = [8;13]
x = A\b

LinearEquations_23

Solution?

2 x1 3x2 4
4 x1 6 x2 7
A = [2 3; 4 6]
b = [4;7]
x = A\b

LinearEquations_24
Simultaneous Linear Equations
 Basic form:

## a11x1 + a12x2 + a13x3 «D1nxn =

b1 a11 a12 a1n x1 b1
a21x1 + a22x2 + a23x3 «D2nxn = a21 a22 a2n x2 b2
b2
«««
an1xn + an2x2 + an3x2 «Dnnxn =
bn

##  Where: an1 an 2 ann xn bn

± aij are known coefficients
± xi are unknowns or
± bi are known right hand Ax b
side values

LinearEquations_25

Solution of equations
2x1 +4x2-2x3=4
4 x1+9x2-2x3=6
-2 x1-3x2+7x3=10

## What is the solution?

demo_lineq3

basicMath_26
 The coefficient matrix A need not be square. If A is m*n,
there are three cases.
± m=n
 Square system.
 Seek an exact solution.
± m>n
 Over determined system.
 Find a least squares solution.
± m<n
 Underdetermined system.
 Find a basic solution with at most m nonzero components.

basicMath_27

Linear Equations

##  Set of linear equations Ax = b can be solved using the

Inverse operation on A
x=inv(A)*b
± Do not use this method
± Inefficient

basicMath_28
backslash \

##  MATLAB has a bunch of methods available to solve a

system of linear equations
 If you desire the solution of Ax = b, then the simplest
method using Matlab to find x is to set x = A\b
A = [ 1 5 6; 7 9 6; 2 3 4]
b = [29; 43; 20]
x=A\b
 Use backslash operator \ (LU decumposition + pivoting)
 If A is an n by m matrix and b is an p by q matrix then
A\b is defined (and is calculated by Matlab) if m=p.
 For non-square and singular systems, the operation A\b
gives the solution in the least squares sense. No error
message
 7KH³\ ´EDFN-slash operator uses a combination of
numerical methods including LU decomposition.

Steps in A\b
Stop if successful
 If A is upper or lower triangular, solve by back/forward substitution
 If A is permutation of triangular matrix, solve by permuted back
substitution (useful for [L,U]=lu(A) since L is permuted)
 If A is symmetric/hermitian
± Check if all diagonal elements are positive
± Try Cholesky, if successful solve by back substitutions
 If A is Hessenberg (upper triangular plus one subdiagonal), reduce
to upper triangular then solve by back substitution
 If A is square, factorize PA = LU and solve by back substitutions
 If A is not square, run Householder QR, solve least squares
problem
Basic optimization

##  optimization means here: determine where a function

y = f(x) takes on either specfic or extreme values
 Zero finding
 Minimization in 1 dimension

basicMath_31

Zero finding

##  fzero: Find zero of a function of one variable

find x satisfying f(x) = 0
 \$QLPSOHPHQWDWLRQRI7'HNNHU¶VDOJRULWKP
 Combination of
± Secant method / quadratic fit extension of Secant method
± Bisection
 While not universally effective, combining techniques
can improve the reliability and speed of convergence
 fzero uses bisection to avoid large steps, other methods
for fast convergence
 syntax:
x = fzero(fun,x0)
± fun user supplied function specifying f(x)
± x0 is an initial guess of an x
Challenges

##  Finding good initial values

± For 1D functions, graphing can be an aid
± Graphing not always possible for some multi-D functions, or
even time-consuming 1D functions
 Analytic methods, if feasible, are always a better choice
than numeric algorithms!
 demo_fzero_1

Minimization in 1 dimension

##  X = fminbnd(FUN,x1,x2) attempts to find a local

minimizer X of the function FUN in the interval x1 < X <
x2. FUN accepts scalar input X and returns a scalar
function value F evaluated at X.
 demo_fminbnd
 demo_fminbnd_2
Maximum?

##  Find maximum of:

1 1
y 5
( x 0.4) 0.01 ( x 0.7) 0.04
2 3

 demo_fminbnd_3

Minimization in n dimensions

##  X = fminsearch(FUN,X0) starts at X0 and attempts

to find a local minimizer X of the function FUN. FUN
accepts input X and returns a scalar function value F
evaluated at X. X0 can be a scalar, vector or matrix.
 Multidimensional unconstrained nonlinear minimization