101
MATLAB introduction

MATLAB Introduction Slides

Embed Size (px)

DESCRIPTION

programming with MatLab

Citation preview

Page 1: MATLAB Introduction Slides

MATLAB introduction

Page 2: 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

• Current in electrical circuits (RLC) – 2nd order differential equation

• Vibration of circular membrane – Bessel functions

• One-dimensional heat flow – partial differential equation (temperature depends on both position and time)

MATLAB provides the tools to solve mathematical models in a programming environment that includes graphing capabilities.

Page 3: MATLAB Introduction Slides

Outline

• Examine basic commands typed at the command prompt

• Arrays

• Equations

• Polynomials

• Plotting

• Systems of equations

• M-files

• Decision-making

• Loops

• Polynomial fitting

Page 4: MATLAB Introduction Slides

Outline

• Examine basic commands typed at the command prompt

• Arrays

• Equations

• Polynomials

• Plotting

• Systems of equations

• M-files

• Decision-making

• Loops

• Polynomial fitting

Page 5: MATLAB Introduction Slides

Command prompt

Start MATLAB by double-clicking on icon or selecting application from the Start menu. The MATLAB desktop will be launched. MATLAB R2006a.lnk

Command prompt “>>”. Can type commands here (or) write and save your own programs (using m-files). Let’s begin with command prompt.

Type the following and hit Enter.

Page 6: MATLAB Introduction Slides

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.

“clear all” removes all variables from the Workspace area.

Page 7: MATLAB Introduction Slides

Outline

• Examine basic commands typed at the command prompt

• Arrays

• Equations

• Polynomials

• Plotting

• Systems of equations

• M-files

• Decision-making

• Loops

• Polynomial fitting

Page 8: MATLAB Introduction Slides

Command prompt

To clear the text from the Command Window, use “clc”. Next, define an array (or matrix; MATLAB = matrix laboratory).

The same 1x5 (row x column) array could be defined as shown.

Default step size is 1.

http://en.wikipedia.org/wiki/Matrix_(mathematics)

Page 9: MATLAB Introduction Slides

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).

Array size is 1x6 (2 rows, 6 columns).

Page 10: MATLAB Introduction Slides

Command prompt

For mxn arrays (two-dimensional), we must use both the row and column indices to access individual elements.

(row, column) = (1, 3) entry is “7”

(row, column) = (2, 5) entry is “15”

Array size is 2x6 (2 rows, 6 columns).

To define a 2-row array, we used a semicolon to mark the end of first row. Both rows must have same number of columns.

Page 11: MATLAB Introduction Slides

An error is generated if the two rows do not have the same number of columns. “CAT” refers to concatenation (or joining arrays).

Error because there are 6 columns in the 1st row and 7 columns in the 2nd row.

Command prompt

Page 12: MATLAB Introduction Slides

Command prompt

Previously defined a row array. Can also define a column array (5x1).

Define array with steps of 0.5 (1x9 array).

Semicolon marks the end of each row.

Page 13: MATLAB Introduction Slides

Command prompt

Let’s define and add two row arrays.

Square each element of the “a” array. The “.” tells MATLAB to perform the squaring operation “^2” term-by-term.

Add the corresponding elements.

The first element of “a” is added to first element of “b”.

Page 14: MATLAB Introduction Slides

Command prompt

Let’s define and add two other arrays.

Use the transpose operator (single quote) to convert row array into column array.

Oops! Arrays must have the same dimensions to be added.

You can learn more in a Linear Algebra course.

Dimensions are: (rows, columns) = (1, 5)

Dimensions are now: (5, 1)

Page 15: MATLAB Introduction Slides

Command prompt

MATLAB has many functions that complete specific tasks. My favorite is “why”. Not very useful, but fun!

Page 16: MATLAB Introduction Slides

Outline

• Examine basic commands typed at the command prompt

• Arrays

• Equations

• Polynomials

• Plotting

• Systems of equations

• M-files

• Decision-making

• Loops

• Polynomial fitting

Page 17: MATLAB Introduction Slides

Command prompt

Let’s define an equation. As an example, consider the volume, V, of a circular cylinder.

r

h

hπrV 2

V = 3015.9 (MATLAB uses scientific notation; value following “e” gives the power of 10).

is defined in MATLAB using “pi”.

Use “*” for multiplication and “^” for power.

Use a radius, r, of 8 and a height, h, of 15.

3103.0159

Page 18: MATLAB Introduction Slides

Given the volume, V, calculate the radius.

Command prompt

πhVr

Note that when using a semi-colon to end a statement (“r = 8;”), the assignment is not echoed to the Command Window.

Used the “sqrt” function.

Original “r” value is overwritten (same value in this case).

Page 19: MATLAB Introduction Slides

Outline

• Examine basic commands typed at the command prompt

• Arrays

• Equations

• Polynomials

• Plotting

• Systems of equations

• M-files

• Decision-making

• Loops

• Polynomial fitting

Page 20: MATLAB Introduction Slides

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).

Command prompt

cbxaxy 2 2a

4acbbx2

1,2

MATLAB has a function “roots” that can be used to find the roots of nth-order polynomials.

Consider the example: 5015x1xy 2

12515

1250141515x

2

1,2

5x1 10x2

Let’s complete the same example using MATLAB.

Page 21: MATLAB Introduction Slides

Use indices of array to call specific value; a = y(1), b = y(2), c = y(3).

Used the “roots” command to find two values of x where y(x) = 0. Same result as quadratic equation.

5015x1xcbxaxy 22

Command prompt

Page 22: MATLAB Introduction Slides

Can also separate elements of row array using commas rather than spaces.

34-40x7x1xy 23

The roots are: ( ) 5i3x1,2 1x3

Command prompt

1i

Page 23: MATLAB Introduction Slides

Command prompt

200110x5xy 24

2000x110x0x5xy 234

The roots are: i20x1,2

i2x1,2

Can factor this polynomial to check the result:

020x105x200110x5xy 2224

2x2 20x2

Page 24: MATLAB Introduction Slides

Command prompt

Let’s look more closely at accessing individual elements of arrays using indices.

3ab

The first element of “a” is 10.

The first element of “b” is:

1000101a1b 33

Step size is -2.

The “.^3” gives the term-by-term cube.

Page 25: MATLAB Introduction Slides

Command prompt

If the “.^” operator is not used, we get an error. This is because the “^3” is attempting to perform: “a*a*a”. The “^” operator requires square arrays; this means that the number of rows and columns must be equal (mxm arrays).

Page 26: MATLAB Introduction Slides

Command prompt

We can also access ranges of elements.

This lists the 5th to 8th elements of “a” and “b”.

-644-8a8b 33

Page 27: MATLAB Introduction Slides

Command prompt

The “find” function is used to identify the indices (not values) of particular elements. It can be used with the relational operators: >, >=, <, <=, ==, ~=.

Find indices of all “b” values > 0.

This is the first 5 elements of “b”.

Show “b” values with indices of 1 through 5.

The “;” suppresses output to Command Window for “a”.

Page 28: MATLAB Introduction Slides

Outline

• Examine basic commands typed at the command prompt

• Arrays

• Equations

• Polynomials

• Plotting

• Systems of equations

• M-files

• Decision-making

• Loops

• Polynomial fitting

Page 29: MATLAB Introduction Slides

Consider the cosine function:

Command prompt

xcos 5y

First, define x and then calculate y.

In this case, it would be better to graph the data to see the result. Use the “plot” function to graph (x, y) data.

Step size in x is:102π

Range is -2 to 2.

Trigonometric functions require inputs in radians ( rad = 180 deg), not degrees, for MATLAB.

Page 30: MATLAB Introduction Slides

Command prompt

-6 -4 -2 0 2 4 6-5

-4

-3

-2

-1

0

1

2

3

4

5

x

y

Individual points are connected by line segments.

The x axis limits are set between -2 and 2 using “xlim”.

Let’s plot only the points next; no line segments.

2π- 2π

Set using “xlabel”.

Figure window

Page 31: MATLAB Introduction Slides

Command prompt

Many figure windows can be opened at the same time (1, 2, 3, …).

Page 32: MATLAB Introduction Slides

-6 -4 -2 0 2 4 6-5

-4

-3

-2

-1

0

1

2

3

4

5

x

yNow only the (x, y) points are shown – red circles are specified by “ro”.

We might like to have higher resolution in x values so the points are closer together and the cosine function is “smoother” when graphed.

102π

Command prompt

x step size

Page 33: MATLAB Introduction Slides

Command prompt

-6 -4 -2 0 2 4 6-5

-4

-3

-2

-1

0

1

2

3

4

5

x

yStep size in x is now:1002π

Graph looks more continuous.

Page 34: MATLAB Introduction Slides

Command prompt

Can plot multiple curves in the same graph. Used blue squares for y1 (larger step size in x1) and red line for y2.

Added “legend” to identify two different curves on single plot.

-6 -4 -2 0 2 4 6-5

-4

-3

-2

-1

0

1

2

3

4

5

x

y

y1

y2

Page 35: MATLAB Introduction Slides

Command prompt

Type “help plot” to learn more.

‘bs’ = blue square

‘r^’ = red triangle (pointing up)

‘k:’ = black dotted line

Page 36: MATLAB Introduction Slides

Command prompt

Let’s use the plotting function to verify identities.

2πxcosxsin 1-1-

xsin a -1 xcos b -1

-6 -4 -2 0 2 4 61.5708

1.5708

1.5708

1.5708

1.5708

1.5708

1.5708

1.5708

1.5708

1.5708

x

a +

b

1.57082π

Plot “a + b”.

102π

x step size

Page 37: MATLAB Introduction Slides

Let’s again use the plotting function to verify identities.

2eexcosh

xx

xe a

-6 -4 -2 0 2 4 60

50

100

150

200

250

300

x

(a +

b)/2

-xe b

Use “exp” function for exponential.

Command prompt

Plot (a + b)/2 and compare to cosh.

xcosh

(a + b)/2

Page 38: MATLAB Introduction Slides

Command prompt

-5 -4 -3 -2 -1 0 1 2 3 4 5-100

-80

-60

-40

-20

0

20

x

y

Find the maximum value of y using “max”.

3-4xy 2

(x, y) = (0, 3)

51st y element

Page 39: MATLAB Introduction Slides

-5 -4 -3 -2 -1 0 1 2 3 4 5-100

-80

-60

-40

-20

0

20

x

y

30x-4xcbxaxy 22

Roots are x = 0.866, -0.866.

Command prompt

Page 40: MATLAB Introduction Slides

Command prompt

-5 -4 -3 -2 -1 0 1 2 3 4 50

20

40

60

80

100

120

x

y

(x, y) = (0, 3)

34xy 2

Find minimum using “min”.

Page 41: MATLAB Introduction Slides

Outline

• Examine basic commands typed at the command prompt

• Arrays

• Equations

• Polynomials

• Plotting

• Systems of equations

• M-files

• Decision-making

• Loops

• Polynomial fitting

Page 42: MATLAB Introduction Slides

Command prompt

Can use MATLAB to solve systems of linear equations.

74x3x59x2x

21

21

Write in vector-

matrix form.

75

xx

4-392

2

1

Vector-matrix form can be represented compactly as: Ax = b

4-392

A

2

1

xx

x

75

b

Can determine x using the inverse of the A matrix: x = A-1b

Perform this operation in MATLAB.

75

4-392

xx 1

2

1

Page 43: MATLAB Introduction Slides

Command prompt

Define the “A” matrix. Note the use of the semicolon to give the 2nd row.

The “inv” function calculates the inverse of a square matrix (the number of rows is equal to the number of columns).

This is more Linear Algebra.

70.028642.37143

50.028692.37142

0.02862.3714

x Check this result. 74x3x

59x2x

21

21

Page 44: MATLAB Introduction Slides

Outline

• Examine basic commands typed at the command prompt

• Arrays

• Equations

• Polynomials

• Plotting

• Systems of equations

• M-files

• Decision-making

• Loops

• Polynomial fitting

Page 45: MATLAB Introduction Slides

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.

Click to begin new m-file.

The Editor screen is launched. We can now type commands in a single program (saved as _____.m) and execute this new program when we are ready.

Page 46: MATLAB Introduction Slides

M-file

Let’s 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.

h

r

2

3

πr3

r2πVh

2r2π400rh2π300C

Page 47: MATLAB Introduction Slides

M-file

“h” is an array. Must use “.” for term-by-term power and division.

Same for “C”.

Find the index of “C” where it is equal to its minimum value.

Determine “r”, “h”, and “C” at this index.

Plot “C” as function of “r”.

Define step/range for r.

Click to execute the m-file. This also saves the program.

Note that you need to have your m-file in the current directory to execute it.

“%” for comments.

Page 48: MATLAB Introduction Slides

M-file

2 3 4 5 6 7 8 9 100.9

1

1.1

1.2

1.3

1.4

1.5

1.6x 10

5

radius (m)

cost

($)

The minimum cost is $91394 for a radius of 4.92 m and height of 3.2949 m.

(4.92, 91394)

Page 49: MATLAB Introduction Slides

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

The blood pressure in the aorta during systole (the period following the closure of the heart’s aortic valve) can be described using:

29.7tsinety 8t-

where t is time in seconds and y(t) is the pressure difference across the aortic valve, normalized by a constant reference pressure (y is unitless).

Page 50: MATLAB Introduction Slides

M-file

29.7tsinety 8t-

This is an oscillating function (sine wave) that decays exponentially. We must decide on step size to plot the function.

Oscillating frequency is 9.7 rad/s. This is: 1.542π9.7f cycles/s (Hz).

The time for one full cycle (or period) is: 0.6481.54

1f1

s.

100 steps per cycle Use “.*” for element-by-element multiplication because t is an array.

Page 51: MATLAB Introduction Slides

M-file

0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5-0.2

0

0.2

0.4

0.6

0.8

1

1.2

time (s)

y(t) 100 steps

per cycle

5 steps per cycle

Red square with dotted line

Page 52: MATLAB Introduction Slides

Outline

• Examine basic commands typed at the command prompt

• Arrays

• Equations

• Polynomials

• Plotting

• Systems of equations

• M-files

• Decision-making

• Loops

• Polynomial fitting

Page 53: MATLAB Introduction Slides

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.

operator meaning< Less than

<= Less than or equal to

> Greater than>= Greater than

or equal to== Equal to~= Not equal to

65

55

55 ~

False = 0

True = 1

False = 0

Can compare arrays in element-by-element fashion. Let’s consider some examples…

Page 54: MATLAB Introduction Slides

Decision-making

6<14, true = 1

x = [6 3 9] y = [14 2 9]

9<9, false = 0

x = [6 3 9] y = [14 2 9]

Page 55: MATLAB Introduction Slides

Decision-making

6~=14, true = 1

x = [6 3 9] y = [14 2 9]

9~=9, false = 0

x = [6 3 9] y = [14 2 9]

Page 56: MATLAB Introduction Slides

Decision-making

6>8, false = 0

x = [6 3 9] 8

9>8, true = 1

x = [6 3 9] 8

Can also compare arrays to a scalar.

Page 57: MATLAB Introduction Slides

The logical operators also make comparisons between arrays. The result of using logical operators is again 1 if true and 0 if false.

Decision-making

operator name definition~ NOT “~A” returns an array with the same dimensions as

“A”; the new array has ones where “A” is zero and zeros where “A” is nonzero

& AND “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

| OR “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

Look at some examples in MATLAB…

Page 58: MATLAB Introduction Slides

Decision-making

z = ~x = ~[0 3 9]

~x(1) = ~0 = 1

~x(3) = ~9 = 0

“~A” returns an array with the same dimensions as “A”; the new array has ones where “A” is zero and zeros where “A” is nonzero

NOT

Page 59: MATLAB Introduction Slides

Decision-making

z = ~x > y = ~[0 3 9] > [14 -2 9]

~x = ~[0 3 9] = [1 0 0]

z = [1 0 0] > [14 -2 9]1 > 14, false = 0

0 > -2, true = 1

NOT

Page 60: MATLAB Introduction Slides

Decision-making

z = ~(x > y) = ~([0 3 9] > [14 -2 9])

[0 3 9] > [14 -2 9]

[0>14 3>-2 9>9]

[0 1 0]

~[0 1 0]

NOT

Page 61: MATLAB Introduction Slides

Decision-making

AND

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

Page 62: MATLAB Introduction Slides

Decision-making

AND

5 & 2, true = 1 0 & 5, false = 0

“z” has same dimensions as “x” and “y”

Page 63: MATLAB Introduction Slides

Decision-making

“x” dimensions are 1x4“y” dimensions are 1x5

“x&y” gives error

AND

Page 64: MATLAB Introduction Slides

Decision-making

OR

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

Page 65: MATLAB Introduction Slides

Decision-making

5 | 2, true = 1 0 | 5, true = 1

“z” has same dimensions as “x” and “y”

0 | 0, false = 0

OR

Page 66: MATLAB Introduction Slides

Decision-making

These results are typically summarized in a truth table.

x y ~x x | y x & y

T T F T TT F F T FF T T T FF F T F F

NOT, AND, OR

Page 67: MATLAB Introduction Slides

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)

x(1) = -2, nonzero

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

x(y) = [-2 4]

Nonzero “x” elements are “-2” and [4]

Page 68: MATLAB Introduction Slides

Decision-making

x = [6 3 9 11] y = [14 2 9 13]

index = find(x < y)

This finds the indices of the comparison (x < y) where the values are true (1).

x = [6 3 9 11] y = [14 2 9 13]6<14 3<2 9<9 11<13True False False True

“find” returns the indices 1 and 4 where the comparison is true (1)

Page 69: MATLAB Introduction Slides

Decision-making

x = [5 -3 0 0 8] y = [2 4 0 5 7]5&2 -3&4 0&0 0&5 8&7True 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]

Page 70: MATLAB Introduction Slides

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).

v0

A h(t)

v(t)

22

02

0

20

tgAsin gt2vvtv

0.5gtAsin tvth

The time is takes to hit the ground is obtained by setting h(t) = 0 and solving for the time, thit.

0.5g

Asinvt 0hit

Page 71: MATLAB Introduction Slides

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.

v0A h > = 6 m

v <= 16 m/s

Decision-making

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.

Need to select step size for t. Choose thit/100.

Write program (m-file) to complete this task. Plot v and h versus t to check results.

Page 72: MATLAB Introduction Slides

Decision-making

Use “find” to determine indices of time where h >= hlim and v <= vlim.

Define “t_true” where conditions are satisfied using “index”.

Find first and last values of “t_true”.

Use “subplot” to make figure with 2x1 panels. Plot lines at hlim and vlim using “line” function.

Page 73: MATLAB Introduction Slides

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.

0 0.5 1 1.5 2 2.50

2

4

6

8

10

h(t)

0 0.5 1 1.5 2 2.515

16

17

18

19

20

time (s)

v(t)

t1 = 0.8649 s t2 = 1.7560 sFor the specified conditions, the velocity limits the range.

Decision-making

Page 74: MATLAB Introduction Slides

Decision-making

The conditional statements if, else, and elseif also enable decision-making in programs.

The basic structure of the if statement is:if logical expression

statementsend

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 >= 0y = sqrt(x);

end

There can be multiple statements within the if statement. There is only one (y = sqrt(x);) here, however.

if logical expression 1if logical expression 2

statementsend

end

if statements may also be nested.

Page 75: MATLAB Introduction Slides

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.

The basic structure of the else statement is:

if logical expressionstatements 1

elsestatements 2

end

Consider the case that y = sqrt(x) for x >= 0 and that y = ex-1 for x < 0.

if x >= 0y = sqrt(x);

elsey = exp(x) – 1;

end

Page 76: MATLAB Introduction Slides

Decision-making

The elseif statement enables an additional decision to be made with an if statement.

The basic structure of the elseif statement is:

if logical expression 1statements 1

elseif logical expression 2statements 2

elsestatements 3

end

Consider the case that y = ln(x) for x > 10, y = sqrt(x) for 0 <= x <= 10, and y = ex-1 for x < 0.

if x > 10y = log(x);

elseif x >= 0y = sqrt(x);

elsey = exp(x) – 1;

end

If not true, then x is <= 10.

If not true, then x is < 0.

1,ey

,xy

,xlny

x

0x10x0

10x

Page 77: MATLAB Introduction Slides

Decision-making

Consider the previous example and write an m-file to determine the result based on the selected x value.

Request “x” value from the user.

Calculate “y” based on “x” input.

Display text and “y” to Command Window.

Page 78: MATLAB Introduction Slides

Decision-making

xlny 10x

xy 10x0

1ey x 0x

Page 79: MATLAB Introduction Slides

Outline

• Examine basic commands typed at the command prompt

• Arrays

• Equations

• Polynomials

• Plotting

• Systems of equations

• M-files

• Decision-making

• Loops

• Polynomial fitting

Page 80: MATLAB Introduction Slides

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:nstatements

end

“m” is the starting value of the loop counter“s” is the step size of the counter“n” is the final value of the loop counter

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.

Page 81: MATLAB Introduction Slides

Loops

Loop counter is “k”. Update “total” value each repetition.

Initialize “total” value to zero.

Display results in Command Window.

Page 82: MATLAB Introduction Slides

Loops

Free vibration of a single degree of freedom spring-mass-damper system can be expressed as:

φtζ1ωcoseφcos

xtx 2n

tζω0 n

02

n

0n01

xζ1ω

xζωx-tanφ

where

m = 2 kg

k = 1106

N/m

x(t)

c = 50 N-s/m

mkωn

km2cζ

0xx0 Initial displacement of mass from equilibrium position

0xx0 Initial velocity of mass

Let initial displacement be 5 mm = 0.005 m and initial velocity be zero. Write m-file to plot x(t) in time steps of 0.0001 s for 0.5 s.

Page 83: MATLAB Introduction Slides

Loops

Use “round” to round number of repetitions to nearest integer.

Use counter “cnt” to index “t” and “x” and write arrays.

Page 84: MATLAB Introduction Slides

Loops

Exponentially decaying cosine wave.

Converted “x” from m to mm.

Page 85: MATLAB Introduction Slides

Outline

• Examine basic commands typed at the command prompt

• Arrays

• Equations

• Polynomials

• Plotting

• Systems of equations

• M-files

• Decision-making

• Loops

• Polynomial fitting

Page 86: MATLAB Introduction Slides

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 y0 25 610 11

bmxy Find m and b for least squares best fit to values of y (dependent variable) at x locations (independent variable).

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.

Page 87: MATLAB Introduction Slides

Polynomial fitting

The sum of the squares of the residuals is:

2223

1i

2ii 11-b10m6-b5m2-b0my-bmxJ

Values of m and b that minimize J are found from: 0mJ

0

bJ

16138b3b280m30mb125mJ 22

028030b250mmJ

0386b30mbJ

Write in vector-matrix form:

38280

bm

63030250

Determine [m b]T using the inverse of the 2x2 matrix. Perform this operation in MATLAB.

Page 88: MATLAB Introduction Slides

Polynomial fitting

Solve for m and b:

38280

63030250

bm 1

m = 0.9

b = 1.8333

The best fit line is: 1.83330.9xy fit

x y0 25 610 11

Find J – the sum of the squares of the residuals.

Page 89: MATLAB Introduction Slides

Polynomial fitting

Find J from the residuals.

1.83330.9xy fit x y yfit (yfit-yi)2

0 2 1.8333 0.02785 6 6.3333 0.1111

10 11 10.833 0.0278

0.1667J

No other straight line will give a smaller J.

1.83330.9xy fit

Page 90: MATLAB Introduction Slides

0 1 2 3 4 5 6 7 8 9 101

2

3

4

5

6

7

8

9

10

11

x

y

datafit

Polynomial fitting

Minimized vertical distance (residual) using least squares fitting.

x y0 25 610 11

1.83330.9xy fit

Page 91: MATLAB Introduction Slides

Polynomial fitting

MATLAB can complete this task using the function “polyfit”. The format for the function call is:

p = polyfit(x, y, n)x – independent variable

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 y0 25 610 11

21 axay Find a1 and a2 for least squares best fit to values of y (dependent variable) at x locations (independent variable).

Page 92: MATLAB Introduction Slides

Polynomial fitting

21 axay

p – row array that contains the polynomial coefficients in descending powers

x y yfit (yfit-yi)2

0 2 1.8333 0.02785 6 6.3333 0.1111

10 11 10.833 0.0278

3

1i

2i2i1 y-axaJ

Best fit line

Page 93: MATLAB Introduction Slides

Polynomial fitting

Example: Bacterial growth

t (min) Bacteria (ppm)

t (min) Bacteria (ppm)

0 6 10 350

1 13 11 440

2 23 12 557

3 33 13 685

4 54 14 815

5 83 15 990

6 118 16 1170

7 156 17 1350

8 210 18 1575

9 282 19 1830http://www.youtube.com/watch?v=gEwzDydciWc

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

Page 94: MATLAB Introduction Slides

Polynomial fitting

1st order fit to data

19

1i

2i2i1 bacteria-ataJ

Best fit line

Page 95: MATLAB Introduction Slides

Polynomial fitting

Large residuals with structure

Page 96: MATLAB Introduction Slides

Polynomial fitting

2nd order fit to data

19

1i

2

i3i22

i1 bacteria-atataJ

Best fit quadratic

Page 97: MATLAB Introduction Slides

Polynomial fitting

Residuals reduced, but some structure remains.

Page 98: MATLAB Introduction Slides

Polynomial fitting

3rd order fit to data

19

1i

2

i432

i23i1 bacteria-atatataJ

Best fit cubic

Page 99: MATLAB Introduction Slides

Polynomial fitting

Smallest residuals with little structure.

Page 100: MATLAB Introduction Slides

Polynomial fitting

0 2 4 6 8 10 12 14 16 18 20-500

0

500

1000

1500

2000

bact

eria

(ppm

)

datafit

0 2 4 6 8 10 12 14 16 18 20-600

-400

-200

0

200

400

time (min)

resi

dual

(ppm

)

0 2 4 6 8 10 12 14 16 18 200

500

1000

1500

2000

bact

eria

(ppm

)

datafit

0 2 4 6 8 10 12 14 16 18 20-100

-50

0

50

100

time (min)re

sidu

al (p

pm)

0 2 4 6 8 10 12 14 16 18 200

500

1000

1500

2000

bact

eria

(ppm

)

datafit

0 2 4 6 8 10 12 14 16 18 20-15

-10

-5

0

5

10

time (min)

resi

dual

(ppm

)

1st order fit

J = 7.9736x105

2nd order fit

J = 1.6776x104

3rd order fit

J = 580.936 ppm

Best fit for this data set

Page 101: MATLAB Introduction Slides

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.