MATLAB Introduction Slides
MATLAB Introduction Slides
Motivation
A fundamental activity of engineering is to describe the world around us
using mathematics. We use mathematical models to describe physical
systems (modeling).
Examples:
Flow of water through orifice 1st order differential equation
Free oscillation of a mass on a spring 2nd order differential equation
Outline
Examine basic commands typed at the command prompt
Arrays
Equations
Polynomials
Plotting
Systems of equations
M-files
Decision-making
Loops
Polynomial fitting
Outline
Examine basic commands typed at the command prompt
Arrays
Equations
Polynomials
Plotting
Systems of equations
M-files
Decision-making
Loops
Polynomial fitting
Command prompt
Start MATLAB by double-clicking on icon or selecting application
from the Start menu. The MATLAB desktop will be launched.
Command prompt >>. Can type commands here (or) write and save
your own programs (using m-files). Lets begin with command prompt.
Type the following and hit Enter.
Command prompt
The variable a is assigned (=) the value of the square root (sqrt) of
243 and the result is echoed to the screen. To clear the variable, use the
clear a command. Note that it disappears from the Workspace area.
Outline
Examine basic commands typed at the command prompt
Arrays
Equations
Polynomials
Plotting
Systems of equations
M-files
Decision-making
Loops
Polynomial fitting
Command prompt
To clear the text from the Command Window, use clc. Next, define an
array (or matrix; MATLAB = matrix laboratory).
http://en.wikipedia.org/wiki/Matrix_(mathematics)
Command prompt
Individual elements of arrays are identified by their index (or indices). For
a 1xn array, it is only necessary to use the column index since there is
just one row.
3rd column in a is 7.
Can also access using both indices: (row,
column) = (1, 3).
Command prompt
For mxn arrays (two-dimensional), we must use both the row and column
indices to access individual elements.
Command prompt
An error is generated if the two rows do not have the same number of
columns. CAT refers to concatenation (or joining arrays).
Command prompt
Previously defined a row array. Can also define a column array (5x1).
Command prompt
Lets define and add two row arrays.
Command prompt
Lets define and add two other arrays.
Command prompt
Outline
Examine basic commands typed at the command prompt
Arrays
Equations
Polynomials
Plotting
Systems of equations
M-files
Decision-making
Loops
Polynomial fitting
Command prompt
Lets define an equation. As an example, consider the volume, V, of a
circular cylinder.
h
V r2h
3.0159 10
Command prompt
Given the volume, V, calculate the radius.
V
h
Outline
Examine basic commands typed at the command prompt
Arrays
Equations
Polynomials
Plotting
Systems of equations
M-files
Decision-making
Loops
Polynomial fitting
Command prompt
Can describe polynomials (often used to fit experimental data) by defining
an array of the polynomial coefficients (highest power to lowest).
For a second-order polynomial, we can use the quadratic equation to
determine the two roots (x values where y(x) = 0).
y ax bx c
2
x1,2
b b 2 4ac
2a
MATLAB has a function roots that can be used to find the roots of nthorder polynomials.
Consider the example:
x1,2
y 1x 2 15x 50
15 15 2 4 1 50 15 5
2 1
2 1
x1 5
x 2 10
Command prompt
y ax 2 bx c 1x 2 15x 50
Command prompt
y 1x 3 7x 2 40x - 34
Can also separate elements of row array
using commas rather than spaces.
x1,2 3 5i
x3 1
( i 1)
Command prompt
y 5x 4 110x 2 200
y 5x 4 0x 3 110x 2 0x 200
The roots are: x1,2 20 i
x1,2 2 i
y 5x 4 110x 2 200 5x 2 10 x 2 20 0
Can factor this
polynomial to
x 2 20
x 2 2
check the result:
Command prompt
ba
b1 a1 10 1000
3
Command prompt
Command prompt
b8 a8 - 4 -64
3
Command prompt
The find function is used to identify the indices (not values) of particular
elements. It can be used with the relational operators: >, >=, <, <=, ==, ~=.
Outline
Examine basic commands typed at the command prompt
Arrays
Equations
Polynomials
Plotting
Systems of equations
M-files
Decision-making
Loops
Polynomial fitting
Command prompt
Consider the cosine function:
y 5 cosx
2
Step size in x is:
10
Range is -2 to 2.
Command prompt
Figure
window
5
4
3
2
1
-1
-4
-2
-3
-5
Set using
xlabel.
-6
- 2
-4
-2
0
x
Command prompt
Many figure windows can be opened at the same time (1, 2, 3, ).
Command prompt
5
4
3
2
1
0
-1
2
x step size
10
-2
-3
-4
-5
-6
-4
-2
0
x
Command prompt
5
4
3
2
1
2
Step size in x is now:
100
0
-1
-2
-3
-4
-5
-6
-4
-2
0
x
Command prompt
5
y1
y2
3
2
1
0
-1
-2
-3
-4
-5
-6
-4
-2
0
x
Command prompt
bs = blue square
r^ = red triangle (pointing up)
k: = black dotted line
Command prompt
1.5708
1.5708
Plot a + b.
1.5708
sin-1x cos-1x
2
a sin x
-1
a+b
1.5708
1.5708
2
1.5708
1.5708
2
x step size
10
1.5708
b cos x
-1
1.5708
1.5708
1.5708
-6
-4
-2
0
x
Command prompt
250
e e
coshx
2
x
a ex
coshx
200
(a + b)/2
b e-x
(a + b)/2
150
100
50
-6
-4
-2
0
x
Command prompt
(x, y) = (0, 3)
20
51st y element
-20
-40
-60
-80
-100
-5
-4
-3
-2
-1
0
x
Command prompt
20
-20
y ax 2 bx c -4x 2 0x 3
Roots are x = 0.866, -0.866.
-40
-60
-80
-100
-5
-4
-3
-2
-1
0
x
Command prompt
y 4x 2 3
120
100
80
60
(x, y) = (0, 3)
40
20
0
-5
-4
-3
-2
-1
0
x
Outline
Examine basic commands typed at the command prompt
Arrays
Equations
Polynomials
Plotting
Systems of equations
M-files
Decision-making
Loops
Polynomial fitting
Command prompt
Can use MATLAB to solve systems of linear equations.
2x1 9x2 5
3x1 4x2 7
2 9 x1 5
3 - 4 x 7
2 9
A
3
4
x1
x
x 2
5
b
7
x1 2 9 5
x 3 - 4 7
2
Command prompt
2.3714
x
0.0286
Check this
result.
2x1 9x2 5
3x1 4x2 7
22.3714 90.0286 5
32.3714 40.0286 7
Outline
Examine basic commands typed at the command prompt
Arrays
Equations
Polynomials
Plotting
Systems of equations
M-files
Decision-making
Loops
Polynomial fitting
M-file
Rather than typing at the command prompt (>>), can write a program to
execute series of commands. This is an m-file in MATLAB.
M-file
Lets write a program (tank.m) to solve the following problem.
A water tank consists of a cylindrical base of radius r and height h and
has a hemispherical top (also radius r). The tank is to be constructed to
hold V = 500 m3 of fluid when filled. The surface area of the cylindrical
part is 2rh and its volume is r2h. The surface area of the hemispherical
top is 2r2 and its volume is 2r3/3.
The cost to construct the cylindrical part of the tank is $300/m2 of surface
area; the hemispherical part costs $400/m2. Plot the cost versus r for 2 r
10 m and determine the radius that results in the minimum cost.
Compute the corresponding height h.
r
2 r 3
V
3
h
r 2
C 300 2 rh 400 2 r 2
M-file
Same for C.
Find the index of C where it is
equal to its minimum value.
% for
comments.
Note that you need to have your m-file in the current directory to
execute it.
M-file
1.6
x 10
1.5
cost ($)
1.4
1.3
1.2
(4.92, 91394)
1.1
0.9
6
radius (m)
10
M-file
The aorta is the largest artery in the body, originating from
the left ventricle of the heart and bringing oxygenated blood
to all parts of the body in the systemic circulation. The
aorta extends down to the abdomen, where it branches off
into two smaller arteries.
http://en.wikipedia.org/wiki/Aorta
M-file
y t e sin 9.7t
2
-8t
9.7
1.54 cycles/s (Hz).
2
1
1
0.648 s.
The time for one full cycle (or period) is:
f 1.54
Oscillating frequency is 9.7 rad/s. This is: f
M-file
1.2
5 steps
per cycle
0.8
0.6
y(t)
100 steps
per cycle
0.4
0.2
0.05
0.1
0.15
0.2
0.25
0.3
time (s)
0.35
0.4
0.45
0.5
Outline
Examine basic commands typed at the command prompt
Arrays
Equations
Polynomials
Plotting
Systems of equations
M-files
Decision-making
Loops
Polynomial fitting
Decision-making
The usefulness of computer programs is
increased by using decision-making
functions. This enables operations to be
completed that depend on the results of
calculations.
The relational operators make comparisons
between arrays.
The result of using relational operators is 1 if
true and 0 if false.
56
False = 0
5 5
True = 1
5 ~ 5
False = 0
operator
meaning
<
Less than
<=
Less than or
equal to
>
Greater than
>=
Greater than
or equal to
==
Equal to
~=
Not equal to
Decision-making
x = [6 3 9]
x = [6 3 9]
y = [14 2 9]
y = [14 2 9]
9<9, false = 0
6<14, true = 1
Decision-making
x = [6 3 9]
x = [6 3 9]
y = [14 2 9]
y = [14 2 9]
9~=9, false = 0
6~=14, true = 1
Decision-making
x = [6 3 9]
8
9>8, true = 1
6>8, false = 0
Decision-making
The logical operators also make comparisons between arrays. The result of
using logical operators is again 1 if true and 0 if false.
operator
name
definition
NOT
&
AND
OR
Decision-making
z = ~x = ~[0 3 9]
~x(3) = ~9 = 0
~x(1) = ~0 = 1
NOT
Decision-making
NOT
z = [1 0 0] > [14 -2 9]
Decision-making
[0>14
NOT
3>-2
9>9]
[0
0]
~[0
0]
Decision-making
z=0&3=0
A&B returns an array the same dimensions as
A and B; the new array has ones where both
A and B have nonzero elements and zeros
where either A or B is zero
z=2&3=1
AND
Decision-making
AND
0 & 5, false = 0
Decision-making
AND
Decision-making
z=0|3=1
A|B returns an array the same dimensions as A
and B; the new array has ones where either A
and B have nonzero elements and zeros where
both A or B is zero
z=2|3=1
OR
Decision-making
5 | 2, true = 1
0 | 5, true = 1
0 | 0, false = 0
OR
Decision-making
These results are typically summarized in a truth table.
NOT, AND, OR
~x
x|y
x&y
Decision-making
We already introduced the find function. find(x) is used to compute an
array containing the indices (not values) of the nonzero elements of x.
x = [-2 0 4]
y = find(x)
Nonzero x elements
are -2 and [4]
x(y) = [-2 4]
x(2) = 0
x(3) = 4, nonzero
y = [1 3]
1st element of x is
nonzero; index is 1
for 1st element
3rd element of x is
nonzero; index is 3
for 3rd element
Decision-making
x = [6 3 9 11]
y = [14 2 9 13]
y = [14 2 9 13]
9<9
11<13
False
True
Decision-making
x = [5 -3 0 0 8]
y = [2 4 0 5 7]
5&2 -3&4
0&0
0&5
8&7
True True False False True
find returns the indices 1, 2, and 5
where the comparison is true (1)
x([1 2 5]) = [5 -3 8]
y([1 2 5]) = [2 4 7]
Decision-making
Consider a projectile that is launched with a speed v0 at an angle A
(relative to the horizontal). Its height, h, and velocity, v, depend on the time
since launch (at t = 0).
v(t)
v0
A
h(t)
ht v 0 t sinA 0.5gt 2
v t v 0 2v 0 gt sinA g2 t 2
2
t hit
v 0 sinA
0.5g
Decision-making
Let v0 = 20 m/s and A = 40 deg (g = 9.81 m/s2). Find the times (between t =
0 and thit) when the height is no less than 6 m and the speed is
simultaneously no greater than 16 m/s.
v <= 16 m/s
v0
A
h>=6m
Solve for v and h as a function of time. Use relational and logical operators
to find times when height and velocity conditions are both true.
Decision-making
Decision-making
Find the times (between t = 0 and thit) when the height is no less than 6 m
and the speed is simultaneously no greater than 16 m/s.
10
h(t)
8
6
4
2
0
0.5
1.5
2.5
20
v(t)
19
t1 = 0.8649 s
18
t2 = 1.7560 s
17
16
15
0.5
1.5
time (s)
2.5
Decision-making
The conditional statements if, else, and elseif also enable decision-making
in programs.
if logical expression
The basic structure of the if statement is:
statements
end
Consider the case that it is only desired to calculate the square root of x if
x is greater than or equal to zero. The logic is: if x >= 0, then calculate y =
sqrt(x). If x is negative, take no action.
if x >= 0
y = sqrt(x);
end
if statements may
also be nested.
if logical expression 1
if logical expression 2
statements
end
end
Decision-making
When more than one action can occur as the result of a decision, use else
and elseif statements along with the if statement.
if logical expression
statements 1
The basic structure of the else statement is:
else
statements 2
end
Consider the case that y = sqrt(x) for x >= 0 and that y = ex-1 for x < 0.
if x >= 0
y = sqrt(x);
else
y = exp(x) 1;
end
Decision-making
The elseif statement enables an additional decision to be made with an if
statement.
y lnx ,
if x > 10
y x,
x 10
0 x 10
y e x 1,
x0
if logical expression 1
statements 1
elseif logical expression 2
statements 2
else
statements 3
end
If not true, then
x is <= 10.
y = log(x);
elseif x >= 0
If not true, then
y = sqrt(x);
x is < 0.
else
y = exp(x) 1;
end
Decision-making
Consider the previous example and write an m-file to determine the result
based on the selected x value.
Decision-making
x 10
y lnx
0 x 10 y x
x0
y ex 1
Outline
Examine basic commands typed at the command prompt
Arrays
Equations
Polynomials
Plotting
Systems of equations
M-files
Decision-making
Loops
Polynomial fitting
Loops
A loop is a structure used to repeat a calculation (or group of statements)
a number of times. The for loop is used when the number of repetitions is
known beforehand. The while loop is used when the loop continues until a
specified condition is satisfied.
for counter = m:s:n
statements
end
Example: Write an m-file to compute the sum of the first 15 terms of the
series 5k2 2k, where k = 1, 2, 3
Use a for loop to complete the task.
Loops
Display results in
Command Window.
Loops
Free vibration of a single degree of freedom spring-mass-damper system
can be expressed as:
- x x
x0
n t
2
1
0
n 0
xt
e
cos n 1 t where tan
cos
1 2 x
0
n
c
k
n
2 km
m
c = 50
N-s/m
k = 1106
N/m
x(t)
m = 2 kg
x 0 x0
x 0 x 0
Loops
Loops
Exponentially decaying
cosine wave.
Outline
Examine basic commands typed at the command prompt
Arrays
Equations
Polynomials
Plotting
Systems of equations
M-files
Decision-making
Loops
Polynomial fitting
Polynomial fitting
We use mathematical models to describe physical systems (modeling).
This often takes the form of collecting data and fitting a function, such as a
polynomial, to the data.
Regression analysis is finding the polynomial that best fits the data in a
least squares sense.
Example: Fit x/y data with a line (1st order polynomial)
x
10
11
y mx b
Best fit is provided by the line that minimizes the sum of the squares in the
vertical (y-direction) differences between the line and data points. These
differences are the residuals.
Polynomial fitting
The sum of the squares of the residuals is:
3
J mx i b - y i m 0 b - 2 m 5 b - 6 m 10 b - 11
2
i1
J
0
m
J
0
b
J
250m 30b 280 0
m
J
30m 6b 38 0
b
250 30 m 280
30 6 b 38
Determine [m b]T using the inverse of the 2x2 matrix. Perform this
operation in MATLAB.
Polynomial fitting
Solve for m and b:
m 250 30 280
b 30 6 38
m = 0.9
b = 1.8333
10
11
Polynomial fitting
Find J from the residuals.
yfit
(yfit-yi)2
1.8333
0.0278
6.3333
0.1111
10
11
10.833
0.0278
J 0.1667
Polynomial fitting
11
data
10
fit
9
8
Minimized vertical
distance (residual) using
least squares fitting.
6
5
4
3
2
1
5
x
10
10
11
Polynomial fitting
MATLAB can complete this task using the function polyfit. The format for
the function call is:
x independent variable
p = polyfit(x, y, n)
y dependent variable
n order of the polynomial fit
p row array that contains the polynomial
coefficients in descending powers
Example: Fit x/y data with line (1st order polynomial)
x
10
11
y a1x a 2
Polynomial fitting
y a1x a 2
Best fit line
3
J a1x i a 2 - y i
i1
yfit
(yfit-yi)2
1.8333
0.0278
6.3333
0.1111
10
11
10.833
0.0278
Polynomial fitting
Example: Bacterial growth
Bacterial growth is the division
of one bacterium into two
daughter cells in a process
called binary fission. Providing
no mutational event occurs, the
resulting daughter cells are
genetically identical to the
original cell. Hence, "local
doubling" of the bacterial
population occurs. Both
daughter cells from the division
do not necessarily survive.
http://en.wikipedia.org/wiki/Bacterial_growth
Video
http://www.youtube.com/watch?v=gEwzDydciWc
t (min)
Bacteria
(ppm)
t (min)
Bacteria
(ppm)
10
350
13
11
440
23
12
557
33
13
685
54
14
815
83
15
990
118
16
1170
156
17
1350
210
18
1575
282
19
1830
Polynomial fitting
J a1t i a 2 - bacteria i
i1
Polynomial fitting
Polynomial fitting
J a1t i a 2 t i a3 - bacteria i
i1
Polynomial fitting
Polynomial fitting
J a1t i a 2 t i a3 t a 4 - bacteria i
i 1
Polynomial fitting
Polynomial fitting
2000
500
0
2
10
12
14
16
18
500
1500
10
12
14
16
18
20
-200
-400
0
10
12
time (min)
14
16
18
20
50
0
-50
-100
10
12
14
16
18
20
10
12
time (min)
14
16
18
20
10
residual (ppm)
500
0
fit
1000
100
200
residual (ppm)
residual (ppm)
fit
1000
20
400
-600
1500
bacteria (ppm)
bacteria (ppm)
bacteria (ppm)
1000
data
data
fit
-500
2000
2000
data
1500
5
0
-5
-10
-15
10
12
time (min)
14
16
18
20
J = 7.9736x105
J = 1.6776x104
J = 580.936 ppm
Summary
Examined basic commands typed at the command prompt
Arrays
Equations
Polynomials
Plotting
Systems of equations
M-files
Decision-making
Loops
Polynomial fitting
More information is available from: William J. Palm III, A Concise
Introduction to MATLAB, McGraw-Hill, 2008.