Вы находитесь на странице: 1из 48

1

Introduction to MATLAB

written by
Mitch Pryor
The University of Texas at Austin
Copyright 2016
Contents

1 Matlab Fundamentals 4
1.1 (Introduction) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Basic Math Calculations in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.2 MATLAB’s whos and clear commands . . . . . . . . . . . . . . . . . . . 7
1.2.3 Scientific Notation and Pre-Defined Constants . . . . . . . . . . . . . . . 7
1.2.4 Mathematical Operations on Variables . . . . . . . . . . . . . . . . . . . . 8
1.3 Vectors and Matricies in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3.1 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3.2 Creating vectors with “:” . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3.3 Matrices in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3.4 Vector and Matrix Operations . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3.5 Extracting an Element From Matrices and Vectors . . . . . . . . . . . . . 14
1.3.6 Extracting a range of entries from a vector or matrix . . . . . . . . . . . . 14
1.3.7 The length or size of a variable . . . . . . . . . . . . . . . . . . . . . . . . 16
1.4 MATLAB m-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.5 MATLAB Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.5.1 Enhancing the plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.5.2 Multiple plots on one set of axes . . . . . . . . . . . . . . . . . . . . . . . 20

2 Programming in Matlab 21
2.1 Programming Structures in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . 21
2.1.1 Create, Name, and Save an m-file . . . . . . . . . . . . . . . . . . . . . . . 21

2
CONTENTS 3

2.1.2 FOR Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22


2.1.3 MATLAB IF Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.1.4 Logic Operators in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.1.5 “While” Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.2 Vectorizing Calculations in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . 28
2.2.1 Compare a manual summation with a vectorized summation . . . . . . . 28
2.2.2 The FIND Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3 Creating your own MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . 31

3 Solving 1st Order ODEs using Matlab 35


3.1 Ordinary Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.1.1 Equations Describing the Motion of a Falling Body . . . . . . . . . . . . . 35
3.1.2 Euler’s Method Numerical Solution for p = 1 . . . . . . . . . . . . . . . . 37
3.1.3 Euler’s Method Using a For Loop . . . . . . . . . . . . . . . . . . . . . . . 39
3.1.4 Convergence of the Numerical Solution . . . . . . . . . . . . . . . . . . . . 40
3.1.5 Euler’s Method Solution for p = 1.1. . . . . . . . . . . . . . . . . . . . . . 42
3.2 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

4 Solving High-order ODEs using Matlab 43


4.1 Solving ODEs using ODE45() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.1.1 Defining an ODE Function . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.1.2 Solving a single ODE Function using ODE45() . . . . . . . . . . . . . . . 44
4.1.3 Solving Sets of ODEs using ODE45() . . . . . . . . . . . . . . . . . . . . 45
4.2 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Chapter 1

Matlab Fundamentals

1.1 (Introduction)

This tutorial is designed to take a user who is familiar with basic programming fundamentals,
but completely new to MATLAB and - through 4 lessons - teach them the core skills necessary
to use MATLAB to

1. Perform basic mathematical operations


2. Understand how (and why) MATLAB’s fundamental constructs are vectors and matrices
3. Familiarize yourself withe MATLAB’s syntax for basic programming constructs such as
IF, FOR, WHILE, etc.
4. Use MATLAB to solve Ordinary Differential Equations (ODEs), even complex ones.

MATLAB (short for MATRIX Laboratory) may best be thought of as an extremely powerful
calculator that let’s you store your calculations as scripts or perform simple calculations using its
command prompt. Furthermore, it has excellent features that allow you to graph or otherwise
output your results in clear and useful formats.

4
CHAPTER 1. MATLAB FUNDAMENTALS 5

MATLAB is huge and I urge to explore all its toolboxes and capabilities; but for now, we need
to getting you ready to use it to visualize the systems we want to control, and the impacts of
our controllers.
Throughout these sections are many example exercizes and problems to test your new skills.
Any new programming environment (just like designing controllers) is best learned by doing so
you are strongly urged to work through the examples and problems as you are reading.
So let’s get to it!

1.2 Basic Math Calculations in MATLAB

In this exercise, you will review how to define variables and perform the most basic mathematical
calculations in MATLAB. Once this exercise is finished, you will be able to use MATLAB much
like you use a handheld calulator.

1.2.1 Variables

MATLAB lets you assign names to numbers just like in calculus. The only difference is that
the left hand side of the equals sign must always have the name and the right hand side must
have the number. In the MATLAB Command Window, reproduce the following

a = 5.0
MATLAB response: a = 5

Now, try putting the variable on the right hand side like this:

5 = a
MATLAB response: ??? 5 = a
! Error...

You receive the error message because MATLAB thinks that you are trying to assign a value
to the number 5 (which already is a value).
MATLAB will always echo the result of what you type unless you end the line with a semicolon.
Try this:

a = 5.0
MATLAB response: a = 5
a = 5.0 ;
MATLAB response: [nothing]
CHAPTER 1. MATLAB FUNDAMENTALS 6

Names for things in MATLAB must start with an uppercase or lowercase letter and contain
only letters, numbers, and underscores. For instance, the following names are acceptable:

scudge 5 = 5 ;
pocket change = 5.63 ;
RocketEngine 2 Thrust = 1453 ;

The following are not.

2more = 4 ;
i-p-freely = 0 ;
lucky# = 13 ;

Typing a number with nothing else on a command line will save its value into a variable named
ans (short for “answer”). Typing a variable name with nothing else on a command line will
print out what its current value is. Type in the three valid variable names and make sure you
get the following responses from MATLAB:

scudge 5
MATLAB response: scudge 5 = 5
pocket change
MATLAB response: pocket change = 5.6300
3.28
MATLAB response: ans = 3.2800

MATLAB variable names are case sensitive! This means, for instance, that a variable named
Velocity is not the same as one named velocity. To demonstrate this, enter the following
and try to guess what the response will be from MATLAB each time before you hit Enter.

Velocity = 2
Velocity
velocity = 4
Velocity
velocity
velocity*Velocity
ans*Velocity
velocity;
CHAPTER 1. MATLAB FUNDAMENTALS 7

1.2.2 MATLAB’s whos and clear commands

MATLAB “remembers” all the variable definitions that you tell it. A list of all the variables
that you defined in MATLAB can be viewed either by typing whos in the Command Window
or looking in the Workspace Window. Take a look at all the variables you have defined.
Using the whos command should give something like this:

whos
MATLAB response: Name Size Bytes Class
==== ==== ===== =====
RocketEngine 2 Thrust 1×1 8 double array
Velocity 1×1 8 double array
a 1×1 8 double array
pocket change 1×1 8 double array
scudge 5 1×1 8 double array
velocity 1×1 8 double array

Quite often, you no longer need old definitions of variables or you just want to get rid of those
old definitions so you can make new variable definitions. To erase your definition for the variable
a, type clear a in the Command Window. Now, look at MATLAB’s list of current variables–
the entry for a should be gone. To erase all your variable definitions, type clear. Now look at
MATLAB’s list of current variables–everything should be gone.
!Be careful with clear since typing clear without a name after it will erase all the memory.
This is a good way to lose hours of work!
! At the same time, it is good practice to use clear between homework problems as it can be
frustrating if MATLAB tries to use variables defined in previous efforts to solve new problems.

1.2.3 Scientific Notation and Pre-Defined Constants

So far, we’ve just been entering numbers close to 1. But if a number is really small or large,
you can use scientific notation. Where you would have written X × 10Y on paper, you can type
XeY . For example, you can enter 6.02 × 1023 like this in MATLAB:

avagadro = 6.02e23
MATLAB response: avagadro = 6.0200e023

MATLAB does a relatively good job of presenting its result in an intuitively clear format. If you
are unhappy with the formatting, you can change the presentation using the format command.
Type help format to learn more about the formatting options available.
PROBLEM OPTION - Last given Fall 2007
CHAPTER 1. MATLAB FUNDAMENTALS 8

Problem 1.1 Now, it’s your turn. Assign 5.98 × 1024 to the name earth mass (in Kilograms).
Write down what you typed at the prompt and MATLAB’s response.

MATLAB also allows you to enter complex numbers. This command assigns a value with a
real component of 4 and an imaginary component of 6 to the variable named y:

y = 4 + 6*i
MATLAB response: y = 4.000 + 6.000 i

Problem 1.2 Assign a value with a real component of 4 × 10−5 and an imaginary component
of 3 × 10− 3 to a variable named x. Write down what you typed at the prompt and MATLAB’s
response.

Some names have values defined by MATLAB. For instance, pi is defined to be π:

pi
MATLAB response: pi = 3.1416

Problem 1.3 MATLAB uses double precision for this and all variables. Write down π to 15
decimal places using the format command. Type help format to learn more about the format
command. You can use the help option to learn more about any MATLAB command.

!Predefined variable variables such as π always start out with the definitions above, but if
you assign a value to any of these special constants, it will overwrite the predefined value and
cause confusion later. Don’t do it!

1.2.4 Mathematical Operations on Variables

Now to use the variables once we’ve assigned a value to them. All of the basic math functions
can be used on both numbers and variables:
x = 3 + 5 Addition
MATLAB response: x = 8
y = 3 - 5 Subtraction
MATLAB response: y = -2
z = 3 * 5 Multiplication
MATLAB response: z = 15
w = 3 / 5 Division
MATLAB response: w = 0.6000
v = 3∧ 5 Exponentiation
MATLAB response: v = 243

You can use these on the same line with each other and you can combine numbers along with
variables:
CHAPTER 1. MATLAB FUNDAMENTALS 9

s = 2*(x + i*y)
MATLAB response: s = 16 - 4 i

The example above also shows how you can also use parentheses to group operations.

Problem 1.4 Type in the lines above and then assign y x + w ∗ w + v to the variable t. What
is the result?

Problem 1.5 Assign (w ∗ x)z + z ∗ y − v to the variable t2. What is the result?

Just like normal arithmetic, there is an order that operations are performed in:

1. Anything inside parentheses

2. Exponentiation and functions (such as sin, cos, etc.)

3. Multiplication and division with the leftmost one being evaluated first in the event of a
tie

4. Addition and subtraction with the leftmost one being evaluated first in the event of a tie

!Where you are unsure about what will be evaluated first, use parentheses! It also makes
what you write easier for others to read.

Problem 1.6 Using the variable definitions above, which two commands below result in the
same value? (Try to answer before typing it into MATLAB!)

(y-57∧ 1.1)/10+a
(y-57)∧ 1.1/10+a
(y-57∧ 1.1)/(10+a)
y-(57∧ 1.1)/10+a
y-57∧ 1.1/10+a

1.3 Vectors and Matricies in MATLAB

MATLAB variable names can hold more than just a single number. A single variable name
can be used to represent vectors and matrices. This section quickly reviews how to create and
perform operations on these constructs. By the end of this tutorial, you will understand why
using vectors and matrices is a core tenant of MATLAB.
CHAPTER 1. MATLAB FUNDAMENTALS 10

1.3.1 Vectors

To create a horizontal (or row) vector, put a list of numbers separated by spaces or commas
between square brackets:

A = [ 1, 2, 3, 4 ]
MATLAB response: A = [ 1 2 3 4 ]

Now you try it with spaces instead of commas and make sure you get the same response from
MATLAB.
Vertical vectors are called column vectors. There are a couple of ways to create a column vector.
First, you can put a list of numbers between square brackets with each number followed by a
semicolon.

B = [ 6; 7; 8; 9 ]
MATLAB response: B = 6
7
8
9

Alternately, you can create a column vector by typing in a row vector and putting a single
quote character, or prime(0 ), just after the right square bracket:

C = [ 1 2 3 4 5 ]0
MATLAB response: C = 1
2
3
4
5

This is probably the easiest way to enter a column vector (because it is the least amount of
typing). Try it for yourself.
This operator is actually taking the transpose of the vector. You can also use the prime after
any MATLAB variable name of a valid vector or matrix to swap its rows and columns. This is
a good way to use a vector as either a row or column vector without keeping two copies around.
Now, type whos to see the list of MATLAB names defined:

whos
Name Size Bytes Class
==== ==== ===== =====
MATLAB response: A 1×4 32 double array
B 4×1 32 double array
C 5×1 40 double array
CHAPTER 1. MATLAB FUNDAMENTALS 11

Notice the “size” column shows how many numbers are in each vector. For row vectors, the
first entry of the size is 1, since there is only one row of numbers. The second component of
the size is the length of the vector. For column vectors, the first component of the size is the
length of the vector and the second component is 1, since there is only 1 column of numbers.

1.3.2 Creating vectors with “:”

When you place two numbers around a colon, MATLAB thinks of it as a vector! Try the
following:

1:10
MATLAB response: ans = [ 1 2 3 4 5 6 7 8 9 10 ]

This is a great way to create a vector of evenly spaced numbers. In fact, the numbers around
the colon don’t have to be integers unless you plan to use the range to extract part of a matrix
or vector.

1.5:10
MATLAB response: ans = [ 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 ]

Notice that the last number is never reached since the count is incremented by 1 each time. If
you would like the increment between columns to be different, you can use an expanded version
of the range syntax:

1.5:2.5:9
MATLAB response: ans = [ 1.5 4 6.5 9 ]

Here, the first and last numbers are the start and end values. The number between the two
colons is the increment. The vector is created by inserting the starting value and then adding
the increment until the end value is reached or passed up.
If you place the range inside a pair of square brackets, you can use the transpose operator (0 )
to create a column vector instead of a row vector:

x = [ 1.5:2.5:9 ]0
MATLAB response: x = 1.5
4.0
6.5
9.0

Problem 1.7 Create a column vector using the range operator that goes from 5 to 35 in steps
of 7. Show the command you used.
CHAPTER 1. MATLAB FUNDAMENTALS 12

Problem 1.8 Create a row vector using the range operator that goes from -3 to 10 in steps of
1.7. Show the command you used.

Problem 1.9 Create a column vector using the range operator that goes from 11 to 6 in steps
of -1.2. Show the command you used.

1.3.3 Matrices in MATLAB

There are a couple of ways to enter a matrix into MATLAB:

• Put each row of the matrix on a separate line:

 K = [ 1 2 3
0 4 6
9 7 2 ]
MATLAB response: K = 1 2 3
0 4 6
9 7 2
• Use semicolons to separate rows of the matrix:

L = [ 1 5 ; 3 4 ; 8 5 ]
MATLAB response: L = 1 5
3 4
8 5

Go ahead and input matricies K and L in MATLAB so we can use them in calculations below.
 
" # 1 1 3
0 2 3 5
Problem 1.10 Consider matrix M: and matrix N:  4 5 6 . Enter the
 
7 3 8 4
9 4 8
MATLAB commands to produce M and N. Make sure they work so we can use the matricies in
some calculations below.

1.3.4 Vector and Matrix Operations

Now that you know how to enter vectors and matrices, you need to learn to manipulate them.
There are many ways to combine scalars, vectors, and matrices – many of them have physical
significance.
CHAPTER 1. MATLAB FUNDAMENTALS 13

1.3.4.1 Matrix + Matrix

To add and subtract matrices and vectors, just add the numbers that are in the same position
in the grid with each other and put the sum in the same grid position in the resulting matrix:

1 2 3 0 5 2 1 7 5
+ =
4 5 6 -2 1 5 2 6 11

Unlike scalars, you can not add any two vectors or matrices! Only vectors and matrices that
are the same exact size may be added together. Otherwise, there will be numbers in one matrix
that don’t have a counterpart in the other.
Use the MATLAB command below to add two of the matricies:

K + N

1.3.4.2 Matrix + Scalar

We can also define addition so that you can add a scalar to a matrix or vector. The MATLAB
command is the same, except that one of the operands next to the plus sign will be a scalar.
In this case, the scalar is added to each number in the whole grid:

L + 5
MATLAB response: ans = 6 10
8 9
13 10

1.3.4.3 Matrix × Scalar

When we multiply a matrix by a scalar, each entry in the matrix is multiplied by the scalar
number. For example,

2*A
MATLAB response: ans = 2 4 6 8

1.3.4.4 Matrix ÷ scalar

Dividing a matrix or vector by a scalar will divide each entry of the matrix or vector by the
scalar, but you can not divide a scalar by a matrix!

Problem 1.11 Define a vector D as [ 4.0 0.0 − 2.0 5.0 ] and write the results of these opera-
tions: A+D, A-(2*D), D-B’, D+19, A/3, 0.5*D
CHAPTER 1. MATLAB FUNDAMENTALS 14

1.3.5 Extracting an Element From Matrices and Vectors

Once you have performed some operations on matrices and vectors, you’ll often want to know
the value of just a few of the entries. You can ask for a single element in a vector by referencing
an “index” inside of parentheses, next to the name of the vector. For example, the first element
(index 1) in the vector D is addressed by typing:

D(1)
MATLAB response: ans = the first element in the D vector

! I know, I know..... Arrays in almost all programming languages start with a zero. This can
be grating at first if our neurons have been so trained to type a zero. But there is a good reason
in MATLAB to start with 1. There will be many, many, MANY times when matrices will be
added, multiplied or otherwise operated on, and have the size of the constructs be same as the
last element in the area does help to keep things simple.
Type the command to return the forth element (index 4) in vector D.
For the vector D in the previous section, i must be between 1 and 4 inclusive. For example, if
you try to access the 5th element:

D(5)
MATLAB response: Error: index exceeds matrix dimensions!

When a MATLAB name is a matrix, you must have two integers inside the parentheses to tell
MATLAB a grid position. Separate the integers with a comma. The first integer is the row
and the second integer is the column:

M(2,3)
MATLAB response: ans = 8

Problem 1.12 Write the command you would use to retrieve the number 6 from the matrix N
(look back in this exercise to see where in N the number 6 is.)

1.3.6 Extracting a range of entries from a vector or matrix

You can use parentheses to look up a range of grid positions. The result is a new vector or
matrix. Where an integer specified a position, two integers with a colon between them specifies
a range of numbers starting at the first integer and ending at the last. To extract part of a vector
from a large one, put a range instead of a position inside the parentheses after a MATLAB
vector variable. For example, try this:

D = C( 1:3 )
CHAPTER 1. MATLAB FUNDAMENTALS 15

MATLAB response: D = 1
2
3

(Note that we just overwrote D with part of vector C.)


The rule works the same for matrices; either or both of the integer indices inside the parentheses
may be replaced with a range. When only one is replaced with a range, you get a vector as the
result. When both are ranges, you get a matrix as the result.
For example, put rows 1 & 2 and columns 2 & 3 of matrix N into a new matrix named NM as
follows:

NM = N( 1:2, 2:3 )


MATLAB response: NM = 1 3
5 6

Now put the first column of matrix N into a column vector named NC:

NC = N( 1:3, 1 )
MATLAB response: NM = 1
4
9

If you want to specify all of the columns or rows in a MATLAB name, use the colon without
any numbers to either side. For example, the previous example could also be written as

NC = N( :, 1 )
MATLAB response: NM = 1
4
9

Problem 1.13 Write the command you would use to store the all the rows but just columns 1
and 2 of matrix N into a matrix named partOfN

Problem 1.14 Write the command you would use to store the all the rows but just columns 1,
2, and 3 of matrix M into a matrix named partOfM

!When solving ODEs, the colon is a critical to making things easy. If your eyes were glazing
over in this section, go for a quick walk and then take another look at the last section.
CHAPTER 1. MATLAB FUNDAMENTALS 16

1.3.7 The length or size of a variable

There are several ways to find the size of vectors and matrices in MATLAB. The length
command will tell you how many numbers are in a vector. For example, try the following

length(D)
MATLAB response: ans = 3

Note that the result is a scalar value! This is the number of elements in the vector D.
The length function only understands MATLAB variables that are vectors. For matrices, use
the size function:

size(L)
MATLAB response: ans = 3 2

emphNote that the result is a vector! You can store the size of one MATLAB variable in another
variable! The first entry in the size vector is the number of rows of the matrix. The second is
the number of columns of the matrix. (In our example, L has 3 rows and 2 columns.)
You can also use the size function on vectors, since they are just a special kind of matrix.

Problem 1.15 Find the sizes of A and M using MATLAB. Write the commands you used and
their results.

1.4 MATLAB m-Files

So far, everything we have been doing has been at the command prompt. This is great for quick
calculations, but sometimes we want to save our results, or run similar calculations without
retyping everything. MATLAB allows us store our commands as scripts called m-files.
To create a new script, simply select New Script (or m-file) from HOME menu, and MATLAB
will automatically open the file and activate the cursor in your new file. Once open, type the
following:

clear all
A = [1 2; 3 4];
B = [ 1 2 1; 2 2 3]
C = A*B

Once done, save the file as scratch.m. Then back at the command prompt, enter:

scratch
CHAPTER 1. MATLAB FUNDAMENTALS 17

You should see values for the matrix B and C printed to the screen. Remember you can
add/remove the semicolons to give yourself extra insight into what your script is doing or to
eliminate clutter in the output. Note that after the script is run, the variable names persist.
Try:

C(1,2)
MATLAB response: 6

!It is generally a very, very good habit to clear any previous variables in memory before
running a script. There are exceptions, but more often than not, it eliminates confusion.

1.5 MATLAB Plots

In this section, we will become familiar with the PLOT command. In the Command Window,
type ’help plot’ and you will see the following:

>> help plot


PLOT Linear plot.
PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix,
then the vector is plotted versus the rows or columns of the matrix,
whichever line up. If X is a scalar and Y is a vector, length(Y)
disconnected points are plotted.

Various line types, plot symbols and colors may be obtained with
PLOT(X,Y,S) where S is a character string made from one element
from any or all the following 3 columns:

y yellow . point - solid


m magenta o circle : dotted
c cyan x x-mark -. dashdot
r red + plus -- dashed
g green * star
b blue s square
w white d diamond
k black v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
CHAPTER 1. MATLAB FUNDAMENTALS 18

For example, PLOT(X,Y,’c+:’) plots a cyan dotted line with a plus


at each data point; PLOT(X,Y,’bd’) plots blue diamond at each data
point but does not draw any line.

PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots defined by


the (X,Y,S) triples, where the X’s and Y’s are vectors or matrices
and the S’s are strings.

To get started using the PLOT command, create an m-file named oscil.m and put the following
in it:

a = 0.5 ;
b = -0.5 ;
t = 0:1:10
for i=1:length(t)
?
?
?
end

Fill in the instructions inside the FOR loop to evaluate these equations for each value of t and
store the results in three vectors (one named x, one named x2, and one named v):

x = sin(at)ebt (1.1)
x2 = sin(at) cos(at) (1.2)
bt bt
v = a cos(at)e + b sin(at)e (1.3)

These equations describe the motion of a damped pendulum; x is the position of the pendulum
and v is the velocity of the pendulum. The pendulum is released from x = 0 with an initial
velocity v = a at tme t = o.
! Be sure to use the for loop to populate the vectors x, x2, and v. Many of you will recall an
easier way to populate the vectors using the ’.’ operator, but we will review this shortcut later.
Right now, we want to make sure you remember how to access the ith element in a vector using
a for loop.
Add the command ’plot( t, x )’ on the last line of oscil.m. You should get a plot like this:
CHAPTER 1. MATLAB FUNDAMENTALS 19

0.35

0.3

0.25

0.2

0.15

0.1

0.05

-0.05
0 2 4 6 8 10

The plot looks kind of jagged because we didn’t sample it at enough points. Also, it would be
nice to see how the function behaved past t = 10.

Problem 1.16 Change the line defining t in the m-file to be t = 0:0.1:70 and rerun the
script. The pendulum must have a really rusty joint, because it almost stops moving after one
swing! Turn in the script file and the plot.

1.5.1 Enhancing the plot

So far, we’ve only plotted position versus time. When you have a bunch of things to plot, it’s
nice to have a title on each plot so you are sure you know what it’s a plot of. To put a title on
a plot, use the title command:

title( ’Position vs. Time’ ) ;

Similarly, you can label the x and y axes of the plot:

xlabel(’Time’) ;
ylabel(’Position’) ;

Add these to your m-file, following the plot command, then run it.
Now that we’ve labeled this plot, we can move on to another one. If you simply entered the
plot command again, our plot of position versus time would be replaced with the new plot. To
tell MATLAB to open another plot window instead, use the figure command:

figure(2) ;
plot(t,v) ;

This command plots velocity versus time in a new window. Create a title and labels for the
new plot.
Suppose we wanted to rescale the axes for some reason. The command to do that is
CHAPTER 1. MATLAB FUNDAMENTALS 20

axis( [0 100 -1 1 ] ) ;

The first two numbers are what you want the bounds on the x axis to be (xmin and xmax ). The
second two numbers are the the bounds on the y axis (ymin and ymax ).

1.5.2 Multiple plots on one set of axes

To put two plots on one set of axes, use the PLOT command as before, but include both sets of
variable names. Try this out:

figure( 3 ) ;
plot( t, x, ’b-’, t, v, ’r:’ ) ;

It is important when generating a plot to pay attention to three things. LABELS: be sure that
labels include units. Be sure that mutliple items on the same graph are uniquely identified,
and make sure that graphs are clear in both color and b/w. RANGE: Make sure the axes are
selected such that the data is visible in the graph. MATLAB usually does a good job of this for
you, but not always. RESOLUTION: Does the range shown let the reader understand what is
going on? For example, data that varies between 1 and 10 will look like a flat line if the axis
range is 0 and 10,000.

Problem 1.17 Set the x label and title of the new plot and then print it out to be turned in.
Adjust the x-axis to show exactly the time span in the problem above divided by 2. Show the
y-axis values between [ -0.1 0.5].

That is the end of Lesson 1. At this time, you should be able to use MATLAB to perform simple
calculations, and see the results in the output console or in a plot. I strongly recommend you
experiment with variations of what we did in this lab until you become comfortable with these
concepts. In the next lesson, we will learn the basic syntax for common programming constructs
so we can perform more complicated calculations.
Chapter 2

Programming in Matlab

2.1 Programming Structures in MATLAB

The simplest programs simple execute the first line, the second line, the third line and so on.
And for simple calculations, this is exactly what you want. But when we use programming
structures (i.e. FOR loops, WHILE loops, and IF statements, we can cause the program to repeat
certain steps, or skip steps. Here we assume you already understand the concept behind these
programming structures and quickly familarize yourself with their syntax in MATLAB.

2.1.1 Create, Name, and Save an m-file

In MATLAB, open up a new m-file. At the top of your m-file, type your name, todays date,
and the name for this lesson:

% Billy Bob

21
CHAPTER 2. PROGRAMMING IN MATLAB 22

% July 4, 1776
% Hwk 1 - Programming Structures in MATLAB

MATLAB ignores everything to the right of the % symbol. In this way, you can type comment
to yourself or others within a MATLAB program without affecting the program.
Before we proceed, go ahead and save you m-file. Call it “structures.m”

2.1.2 FOR Loops

You can give MATLAB a vector and have it execute a list of commands using the value set to
each entry of the vector, one at a time. In other words:

for variable = vector


 instructions to be repeated
end

MATLAB assigns a variable (called the counting variable) to be the first entry of the vector
and runs the “instructions to be repeated”. Then, MATLAB moves to the next entry in the
vector, assigns that value to the vector, and runs the instructions again.
Type this example into your m-file:

clear
for x = [ 1 3 5 ]
x
end

Notice that we started out with the clear command which erases any previously stored variables
in MATLAB. We also indented the line within the for loop–this is a good idea because it makes
the program easier to read. If we have more than one line between the “for” and the “end”
statements, we would have indented them all. Unlike other programming languages you may
have used, MATLAB generally tries to restrict paranthese to mathematical formulations, which
makes for a slightly more verbose, but readable syntax.
Now, save and then run your MATLAB file (click the Run button or select Run from the Debug
menu). MATLAB should print out the value of x three times in the Command Window. Each
time, x has been changed to an entry of the vector in the for command. Your result should
look like this:

MATLAB response: x = 1
x = 3
x = 5
CHAPTER 2. PROGRAMMING IN MATLAB 23

You can also use the range notation (“:”) to generate a vector for the for loop:

for x = 1:2:5
x
end

will produce the same results as the previous example.

Problem 2.1 Enter the following commands in your m-file and run it if myValue equals 9.
What size is y and what will be in each entry of y?

n = myValue;
for x = 1:n
y(x) = exp(x) ;
end
y

Now, type whos in the Command Window to see what is left behind after running the for loop
and assuming myValue equals 10:

whos
Name Size Bytes Class
==== ==== ===== =====
MATLAB response:
x 1×1 8 double array
y 1×10 80 double array

Note that x is just a scalar! If you want x to hold the vector of all the values that the instructions
were evaluated with, then you need to define it before hand:

x = 1:10 ;
for i=x
y(i) = exp(x(i)) ;
end

! Always put a semicolon at the end of each instruction inside a for loop unless you really
want to see the MATLAB response for every command repeated over and over. For example,
leaving the semicolon off of y(x) = x + 1 below will print out the y vector once for each value
of x!

for x=1:6
y(x) = x + 1
end
CHAPTER 2. PROGRAMMING IN MATLAB 24

Type this into your m-file and run it. You should get the response:

MATLAB response: y = 2
y = 2 3
y = 2 3 4
y = 2 3 4 5
y = 2 3 4 5 6
y = 2 3 4 5 6 7

2.1.2.1 Indexing and FOR Loops

The for loop is great for generating function values to plot. But you have to be careful not to
confuse the “index” of a vector (an integer greater than zero) with “the value to evaluate the
function at” (any real number). The following problem demonstrates this.

Problem 2.2 The following example won’t work. Why not? Hint: How would you display the
second element in the vector y?

for x=1:0.5:6
y(x) = x + 1
end

The easiest way around this problem is to define x as all the values in the loop and use some
other variable (like i) as the counting variable:

x=1:0.5:6
for i=1:length(x)
y(i) = x( i ) + 1
end

Try it now. Type it into your m-file and run it.

Problem 2.3 Now Let’s try on our own. Use a for loop and MATLAB to plot the following
relationship. x=1:.05:5 and y=cos(x) Turn in both your m-file and the plot. (Assume x is
in radians and does not need to be converted. It is in general a good idea to always include
information on the units in the axis labels.)

2.1.2.2 Nested FOR Loops

Sometimes, you’ll need to put one loop inside another. This is called nesting loops. Create a
new script file named nested.m and put this in it:
CHAPTER 2. PROGRAMMING IN MATLAB 25

row = [1 2 3 ] ; % Our starting values


factor = [ 1 10 100 1000 ]’ ; % The multiplication factor for each row
for i=1:length(factor) % ‘‘outer loop’’
for j=1:length(row) % ‘‘inner loop’’
A(i,j) = factor(i)*row(j) ;
end
end
A % print out the resulting matrix

!If you have not done this already, realize you should be able to select the text in this manual
and cut & paste the scripts into your m-file.
Now, run the script. The output of your m-file should be the following matrix
 
1 2 3
 10 20 30 
A=
 
100 200 300

 
1000 2000 3000

Problem 2.4 Edit nested.m so that row = [ -2 -1 0 1 2 ] . Run the m-file. Using
MATLAB vector multiplication, how can you produce the matrix A without using any FOR
loops?

! Be careful not to make nested loops too big! If you nest one loop inside another and both
go from 1 to 1000, the instruction inside both loops gets run 1000 * 1000 = 1,000,000 times!
That can slow down even a fast computer.

2.1.3 MATLAB IF Statements

Sometimes physical systems are described by piecewise continuous functions. For instance
(
5x for x ≤ 2
F orce =
0 x>2
MATLAB can do this using the IF statement. An IF statement has the following syntax:

if ( condition )
instructions
end

where “condition” is something that can be evaluated as either true or false and “instructions”
are MATLAB commands that get executed only when “condition” is true. The “condition”
must be met in order for the IF statement to execute the instructions. For example, we could
calculate the force from above like this:
CHAPTER 2. PROGRAMMING IN MATLAB 26

Force = 5 * x ;
if ( x $>$ 2 )
Force = 0 ;
end

You can also tell MATLAB to run one piece of code when an expression is true and another
piece of code when it is false.

if ( x <= 2 )
Force = 5 * x ;
else
Force = 0 ;
end

You can also chain them together to handle many cases using the elseif command:

if ( x < 0 )
Force = 0 ;
elseif ( x > 10 )
Force = 100 ;
else
Force = 50 ;
end

This command defines Force to match this equation:




 0 x<0
F orce = 50 for 0 ≤ x ≤ 10
100 x > 10

Problem 2.5 Create a script file named force.m and define force to be


0 x≤0
F orce = 5x for 0 < x < 10
 50

x ≥ 10

Inside the script file force.m, define x=1:20 and write a for loop around the IF statement that
sets a vector F equal to Force evaluated at each x. Plot the result using plot( x, F ). Add
both a title and labels for each axis. Print out a copy of the script and the plot to turn in.
CHAPTER 2. PROGRAMMING IN MATLAB 27

2.1.4 Logic Operators in MATLAB

Here’s a list of all the things you can check for in the condition of an IF statement:

< less than


> greater than
<= less than or equal to
>= greater than or equal to
== exactly equal to (Note: Two equal signs will check to see if
variables are equal. One equal sign will assign a value to the
variable on the left!)
∼= not equal to

You can create more complex conditional statements using the following symbols:

& and
or
∼ not

Here are a couple of examples showing how to use the second list of symbols:

1. This example will only execute the commands if x is strictly between 4 and 10:

if ( x>4 & x<10 )


( commands )
end

2. This example will only execute the commands if x is not between 10 and 60:

if ( x<10 | x>60 )
( commands )
end

Problem 2.6 Construct a statement that will be true if x is equal to 12 or -3.

2.1.5 “While” Loops

Sometimes, you even want the number of times an instruction is executed to be based on
whether some expression is true or false. That’s what the while structure is used for. It’s
syntax is

while ( condition )
instructions
end
CHAPTER 2. PROGRAMMING IN MATLAB 28

An example of a while loop is

response = 1;
while(response ~= 0)
beep
disp(’Well hello there!’)
response = input(’Enter a number > 1 to repeat, Enter 0 to stop’);
end

Since we will mainly be using MATLAB to perform fixed scripts, we won’t spend too much time
on its ability to dynamically interact with the user, but you can see above that the capabilities
do exist in MATLAB.

Problem 2.7 Create an m-file called userrepeat.m and enter the example above. Run it to
make sure it works properly. Modify this program so that it counts up and displays the number
of times the user told the computer to repeat. Print out and turn in your m-file and a copy of
the console output.

2.2 Vectorizing Calculations in MATLAB

Unlike most other programming languages, MATLAB is intrinsically vector based in the way
that it stores and manipulates data. This laboratory exercise demonstrates the usefulness of
performing vectorized calculations in MATLAB. Vectorization of greatly reduces the need for
structures like /mvFor loops and conditional statements, thereby reducing the MATLAB code
required for many types of programs. Also, vectorized calculations take advantage of powerful,
optimized software components that increase calculation speed.

2.2.1 Compare a manual summation with a vectorized summation

Write a MATLAB script (call it “myVectorize.m”) that performs the following summation using
a FOR loop:

N
X
i2 (2.1)
i=−N

You should have something like:

% Perform a single summation manually with a for loop


clear all
N = 100000;
CHAPTER 2. PROGRAMMING IN MATLAB 29

sum = 0;
for i = - N:N
sum = sum + i∧ 2;
end
sum

! Note that MATLAB has thousands of built in functions. So be very careful to pic file names
that will not accidentally overwrite MATLAB functions. This is actually a relatively cool
feature since if you have a sin.m file in your working folder, MATLAB will use it before using
its sin function. But it is probably more clear (and less buggy) if you use mySin.m. unless your
goal is to force existing code to you use your sine function instead of MATLAB’s sine function.
Let’s see how long it takes the computer to carry out this calculation. To do this, we will use
the tic and toc commands in MATLAB. Type “help tic” in the Command Window. You
should see

>> help tic

TIC Start a stopwatch timer.


The sequence of commands
TIC, operation, TOC
prints the number of seconds required for the operation.

Put the tic and toc commands around your For loop and run it.
For comparisons, let’s do the same thing with a “vectorized” calculation, rather than a FOR loop.
You’ll need to use the sum command. You can type “help sum” in the Command Window to
see how to use the command if you are not sure. You need to create a vector i and apply the
sum command. You should get something like this:

% Perform a summation using vectors clear all


N = 100000;
tic
i = [-N:N];
sum(i.∧ 2)
toc

Put this at the bottom of myVectorize.m. Run the script and compare the times required to
complete the summation.

Problem 2.8 Why do we use “.∧ ” rather than simply “∧ ”? Which routine is faster? Which
script required less typing? Run these routines for N = 30,000, 300,000, and 3,000,000 and
neatly tabulate the results to be turned in, along with the answers to the questions above. Turn
in both your table and scripts.
CHAPTER 2. PROGRAMMING IN MATLAB 30

2.2.2 The FIND Command

Now, let’s learn how to perform vectorized conditional calculations using the FIND command.
As an example, let’s imagine we are at the Texas Motor Speedway measuring the speed of 100
different race cars as they pass by. Here is a MATLAB script that simulates the speed of 100
different race cars by assuming that they obey a normal distribution:

% Here is a theoretical model for the speed of


% cars on a race track:
clear all;
Ncars = 100; % This is the number of cars
carnumber = [1:Ncars]; % These are the numbers on the cars
speed = 150 + 30*randn([Ncars,1]); % Speeds fit a normal distribution
figure(1), plot(carnumber,speed,’b*’)
xlabel(’car number’), ylabel(’speed [mph]’)

Type this into a m-file on your computer and run it.

Problem 2.9 What does the RANDN command do?

Now, let’s use the FIND command to plot the velocity of cars traveling at least 180 mph. To
figure out how to do this, type “help find” in the Command Window and read about FIND:

>> help find

FIND Find indices of nonzero elements.


I = FIND(X) returns the indices of the vector X that are
non-zero. For example, I = FIND(A>100), returns the indices
of A where A is greater than 100. See RELOP.

Here is how to do it. Type this script in, run it, and confirm that you get a plot similiar to the
one in Figure 2.1.

indices = find(speed>180);
figure(2)
plot(carnumber,speed,’b*’, carnumber(indices),speed(indices),’ko’)
xlabel(’car number’), ylabel(’speed’)

Use the TITLE command to put your name at the top of the plot. As you can see, the find
command is very powerful and saves you a lot of time writing FOR loops and IF statements.
CHAPTER 2. PROGRAMMING IN MATLAB 31

250

200

150
speed [mph]

100

50

0
0 20 40 60 80 100
car number

Figure 2.1: A plot of car velocity vs. car number.

Problem 2.10 Turn in your script and the plot generated above.

Problem 2.11 Without using the find command, generate a plot that shows all cars whose
speed is greater than 185 mph. Turn in the plot and script.

2.3 Creating your own MATLAB Functions

MATLAB has a lot of built in functions. Here are just a few:

sin - Sine.
asin - Inverse sine.
cos - Cosine.
acos - Inverse cosine.
tan - Tangent.
atan - Inverse tangent.
exp - Exponential.
log - Natural logarithm.
log10 - Common (base 10) logarithm.
sqrt - Square root.
CHAPTER 2. PROGRAMMING IN MATLAB 32

There are hundreds of other built in mathematical functions. But sometimes, you might want
to create you very own function that you can use in you MATLAB programs. For example:

3  3 
f (x) = x − 10.535x2 + 25.697x − 18.099 (2.2)
500

g(x) = −1.25xesin(x) e−3x − 71.4 (2.3)


(
0 for x < 12
h(x) = (2.4)
12x2 − 12 for x ≥ 12

If we create a MATLAB function for these three equations, we can evaluate them without
having to type the whole thing each time we want a number. Functions are named just like
variables: they must start with a letter (upper- or lower-case) and any subsequent characters
must be letters, numbers, or underscores.
! Parentheses after a function name mean something different than parentheses after a variable
name! When they follow a variable name, they indicate a position or range of positions inside
the matrix associated with that variable. When parentheses follow a function name, they
contain arguments to the function. . . or extra information it needs to compute the return value.
To create a function, open up a new m-file and give it the name of the function. As an example,
let’s create a function f that returns the value of f (x) given x. So, create a file named f.m.
The first line of a function’s script file must begin with a line telling MATLAB the name of the
function, what information it will need as arguments, and what information it returns. It looks
like this

function value=f(comma-separated arguments)

The first word (function) will always be the same. After that, there’s a space and a variable
name (value in this case). That variable is where you store the results of the function. There’s
an equal sign following that and then the name of the function (f for our example).
The name of the m-file must be the same as the name of the function. Then, inside parentheses,
place a list of variable names that the user must supply numerical values for in order for you
to assign a value to the result variable, value. The variables inside the parentheses are called
the argument list of the function.
Once you have the function line typed in, you can add as many MATLAB instructions after it
as you like. Each one will be executed in order until MATLAB reaches the end of the file. It
then sends the the return value variable (value) back to the user by replacing the function call
with the number in value.
CHAPTER 2. PROGRAMMING IN MATLAB 33

Inside the function, you can’t access any variables that the user may have defined on the
command line or an m-file that uses the function. Only the variables on the argument list and
any you create inside the function can be accessed within the function. Similarly, outside the
function you can’t access any variables that may have been defined inside the function. All you
get to see is whatever is in the return value variable, value.
So, here’s all of what the script file should contain for our function f:

function value=f(x)
value = (3/500)*(x.^3 - 10.535*x.^2 + 25.697*x - 18.099) ;

! Notice that we are using the scalar operator “.∧ ” to raise x to a power as opposed to the
“∧ ” vector/matrix operator. If x is a scalar (a simple number), there is no affect of using “.∧ ”

as opposed to the “. ” operator. But, if x a vector (say, x = [1 2 4]), then the equation has
completely different meaning.
Once you’ve typed the function above, save the script. In order to use the function, MATLAB
must be able to find it on your computer. The simplest way to accomplish this is to set your
Current Directory to that which contains the function file f.m. You can do this in the Current
Directory window or by typing the Linux style ’cd’ command at the command prompt.
Execute the function in the command window:

f(2.3)
MATLAB response: ans = -0.01536
x
MATLAB response: ??? Undefined variable or function.
value
MATLAB response: ??? Undefined variable or function.

3
Sure enough, −0.01536 = 500 (2.33 − 10.535(2.3)2 + 25.697(2.3) − 18.099). The other commands
just show that MATLAB doesn’t let you see the values of variables inside a function’s script.
! This is not the same as other script files – variables you create in other script files will be
accessible on the command line after you run the script.
In the example above, we input a simple number into the function f. MATLAB also allows us
to input a vector, or even a matrix into a function.

Problem 2.12 What is the output from the following commands if entered in the Command
Window?

inputvector = [0 3 3.3];
f(inputvector)
CHAPTER 2. PROGRAMMING IN MATLAB 34

Now, create a new function m-file called fscalar.m that contains the following:

function value=fscalar(x)
value = (3/500)*(x^3 - 10.535*x^2 + 25.697*x - 18.099) ;

Problem 2.13 Once you have saved your function “fscalar.m,” execute the following com-
mands in the Command Window

fscalar(0.67)
vectorinput = [1 -2 2];
fscalar(vectorinput)

What are the results of these commands? Why?

Problem 2.14 Create function files g and h for the other two equations. Make sure that the
function g can accept either a simple number or a vector, or a matrix. Function h will require
the use of an if statement to set value. Function h should accept a scalar variable (not a
vector or matrix). Print out the functions to turn in.
Chapter 3

Solving 1st Order ODEs using


Matlab

3.1 Ordinary Differential Equations

At this point, you should know enough about MATLAB that we can start to use it to solve the
type of problems we need to solve in a dynamics and controls course. This includes the ability
to solve differential equations are the form for most dynamic models in any discipline. As the
systems examined become more complex (i.e. include friction, not assuming point masses, etc.)
it may no longer be possible to solve the derived ODEs analytically and they must be solved
numerically. To illustrate a few numerical methods and their MATLAB implementation, we
will solve a simple differential equation that describes the motion of a falling body including
the effects of air resistance.

3.1.1 Equations Describing the Motion of a Falling Body

The motion of an object that falls under the influence of gravity and air friction is governed by
the following differential equation

35
CHAPTER 3. SOLVING 1ST ORDER ODES USING MATLAB 36

dv/dt = −ρv p − g (3.1)

where v is the velocity, t is time, ρ is the drag coefficient, g is acceleration due to gravity (32
feet/s), and p is a constant that can have a value between 1 and 2. For relatively slowly falling
objects (a parachutist, for example), p = 1. The exact solution to Eqn. (3.1) is given by

v(t) = Cexp(−ρt) − g/ρ (p = 1) (3.2)

where C is a constant determined from the initial conditions. In this exercise, we will assume
that the falling object starts from rest so that v = 0 at t = 0. Applying this condition to
Eqn. (3.2) gives 0 = C − g/ρ or C = g/ρ.. We will use the analytical solution to determine the
accuracy of the proposed numerical methods.
For other falling objects, a more accurate description might be given by p = 1.1 in Eqn. (3.1).
In this case, an exact analytical solution does not exist, so we are forced to numerically solve
the differential equation to describe the object’s motion.

Problem 3.1 Create an m-file called falling.m. At the top of your m-file, place the CLF
command (this clears the current figure window every time you run your m-file). Enter the
necessary commands to create a smooth line plot of Eqn. (3.2) for t = 0 to 5 seconds with
ρ = 1.2 and g = 32 f eet/s2 . The x-axis should have units of seconds, the y-axis should
have units of feet per second, and the curve should be a smooth line. Label the x and y axes
appropriately and create a title for the plot that includes your name. Put your name in the title
of the plot. Turn in your figure.

Your figure should look similar to the following, where ρ = 1.5 and t = 3 seconds. If necessary
change the parameters in program to these to confirm you entered the function correctly, but
be sure to turn in a graph with the designated elapsed time and drag coefficient.

Billy Bob Parachute Plot


0

-5

-10
Velocity (ft/s)

-15

-20

-25
0 0.5 1 1.5 2 2.5 3
Time (s)
CHAPTER 3. SOLVING 1ST ORDER ODES USING MATLAB 37

3.1.2 Euler’s Method Numerical Solution for p = 1

The simplest method of numerically solving differential equations is Euler’s method. Here is a
simple way to use Euler’s method to solve Eqn. (3.1) for p = 1:

1. Specify the initial condition on v:


v(0) = 0

2. Calculate the initial rate of change of v (from Eqn. (3.1) with p = 1):

dv
|t=0 = −ρv(0) − g
dt

3. Estimate the value of v at some small amount of time later (t = ∆t):

dv
v(∆t) = v(0) + ∆t |t=0
dt

4. Calculate the rate of change of v at the new time (t = ∆t):

dv
|t=∆t = −ρv(∆t) − g
dt

5. Estimate the value of v at some small amount of time later:


dv
v(2∆t) = v(∆t) + ∆t |t=∆t
dt

6. Calculate the rate of change of v at the new time ((t = 2∆t):

dv
|t=2∆t = −ρv(2∆t) − g
dt

7. Estimate the value of v at some small amount of time later:


dv
v(3∆t) = v(2∆t) + ∆t |t=2∆t
dt

Mathematically, Euler’s method uses a simple linear extrapolation to estimate the value of the
velocity at some future time, based on the velocity at the present time. The accuracy of the
estimated velocity generally increases as the step size, ∆t, decreases. In MATLAB syntax, steps
1–7 can be written as

clear all;
g = 32; % in feet per second
rho = ?.?; % the drag coefficient from the problem above
CHAPTER 3. SOLVING 1ST ORDER ODES USING MATLAB 38

deltat = 0.5; % the time step


v(1) = 0; % initial condition
t(1) = 0; % initial time
dvdt(1) = -rho*v(1) - g;
v(2) = v(1) + deltat * dvdt(1);
t(2) = deltat;
dvdt(2) = -rho*v(2)- g;
v(3) = v(2) + deltat*dvdt(2);
t(3) = 2*deltat;
...
...
...

where we have replaced variable names with MATLAB friendly names and have chosen ∆t = 0.5
second. Note that the integers inside the parentheses reference an element inside a vector. We
are creating a vector of velocities, v, and a vector of times, t. The MATLAB commands that
correspond with steps 6–7 have not been included above.

Problem 3.2 Enter the commands for steps 1–7 at the bottom of falling.m. Run your m-file.
Then type “v” in the Command Window and you can see the numerically calculated values for
the velocity of the parachutist. Turn in the resulting vector v.

Problem 3.3 At the bottom of falling.m, enter the commands to overlay a plot of your numer-
ically calculated values of velocity (how many data points will you generate?) on top of the exact
solution you plotted in earlier. The easiest way to do this is with the HOLD ON command—this
prevents your earlier plot (the exact solution) from being erased. To distinguish your numerical
solution from the exact solution, plot your numerical solution using a circle (instead of a line).
Turn in your plot.

You should have a plot that looks similar to:


CHAPTER 3. SOLVING 1ST ORDER ODES USING MATLAB 39

Billy Bob Parachute Plot


0

-5

-10
Velocity (ft/s)

-15

-20

-25
0 0.5 1 1.5 2 2.5 3
Time (s)

Again, if you use a drag coefficient of 1.5 over 3 seconds, the graphs should be identical. Notice
that the numerical solution does not match the exact analytical solution. This is due to the
inaccuracy of the numerical solution.

3.1.3 Euler’s Method Using a For Loop

We can improve the accuracy of the numerical solution by decreasing our step size, ∆t, and
increasing the total number of steps we take over the time interval of our plot. By using a FOR
LOOP, we can perform many steps without having to type in each step over and over again.
The FOR loop would look like this:

% Euler’s method with a For Loop


clear all;
g = 32; % in feet per second
rho = ?.?; % the drag coefficient given in the first problem
stoptime = ?.?; %the time elapsed given in the first problem
deltat = 0.25; % the time step
v(1) = 0; % initial condition
t(1) = 0; % initial time
for i=1:round(stoptime/deltat)

end

Notice we have chosen a smaller value of ∆t (0.25 seconds). We set up the FOR loop to run
from i = 1:round(timestop/deltat). The ROUND command rounds off a real number to the
CHAPTER 3. SOLVING 1ST ORDER ODES USING MATLAB 40

closest integer value in case the proposed time step does not divide evenly into the total elapsed
time.

Problem 3.4 For the designated time given in problem one, how many data points will be
generated with a time step of 0.25 seconds?

Problem 3.5 Type in your Euler’s method using a FOR loop at the bottom of falling.m. Enter
the commands to overlay a plot of your result with deltat = 0.1 on top of the exact solution and
the deltat = 0.5 solution. To distinguish your new solution from the previous solutions, plot
your new solution using the ’r.’ plot option. Turn in the lines of MATLAB required to generate
your result.

You should have a plot that look similar to this one below that adds a line for a deltat=0.25.

Billy Bob Parachute Plot


0

-5

-10
Velocity (ft/s)

-15

-20

-25
0 0.5 1 1.5 2 2.5 3
Time (s)

3.1.4 Convergence of the Numerical Solution

As you can see from previous section, care must be taken to choose a sufficiently small numerical
step size to assure accuracy. However, it is a bad idea to simply set the step size ∆t to some very
small value and assume the answer is correct. An extremely small step size can slow down the
calculation to the point where your computer takes several minutes, or even days, to perform
the calculation. In addition, extremely small step size can lead to inaccuracies resulting from
the finite number of digits carried through the calculation by your computer (i.e. round-off
error).
To determine if a numerical solution is accurate, it is a good idea to start with a fairly large
step size and gradually reduce the step size. As the step size is reduced, the numerical solution
will gradually come closer and closer to the exact solution. At some point, reducing the step
CHAPTER 3. SOLVING 1ST ORDER ODES USING MATLAB 41

size will have little affect on the result, at which point the numerical solution is said to have
converged.
Using ρ = 1.5, change the timestep to deltat = 0.025 and run your m-file to obtain the following
plot:

Billy Bob Parachute Plot


0

-5

-10
Velocity (ft/s)

-15

-20

-25
0 0.5 1 1.5 2 2.5 3
Time (s)

Or change the timestep to deltat = 0.01 and run your m-file to obtain the following plot:

Billy Bob Parachute Plot


0

-5

-10
Velocity (ft/s)

-15

-20

-25
0 0.5 1 1.5 2 2.5 3
Time (s)

Notice that the numerical solution has changed very little by reducing deltat from 0.025 to
0.010. This indicates that the solution has converged. Therefore, you can be reasonably sure
that the answer is correct for deltat = 0.01. In this case, you are fortunate to know the exact
analytical solution and we see that the numerical solution, with deltat = 0.01 gives the same,
correct result.
CHAPTER 3. SOLVING 1ST ORDER ODES USING MATLAB 42

3.1.5 Euler’s Method Solution for p = 1.1.

Problem 3.6 Using the drag coeefficient you were given in the first problem, generalize the
result of the previous section for p=1.1 in Eqn. (3.1). Assure that your results have converged
by gradually reducing the step size until the shape of the curve no longer changes. Overlay the
p = 1.1 result with the results of the previous sections. Label each curve with the text tool.

You should obtain a plot similar to this one:

Billy Bob Parachute Plot


0

-5

-10
Velocity (ft/s)

p = 1.1, ∆ t = .01
-15

-20 p=1, ∆ t = .01


p=1, ∆ t = 0.5

-25
0 0.5 1 1.5 2 2.5 3
Time (s)

3.2 Conclusion

This brief overview should allow you to now extend MATLAB’s capabilities to include addi-
tional numerical algorithms discussed in class including the midpoint, Heun’s, and Runga-Kutta
methods.
Chapter 4

Solving High-order ODEs using


Matlab

4.1 Solving ODEs using ODE45()

Previously, you learned how to write an m-file that used Euler’s method to solve a single
1st order differential equation. In this section, you will learn how to use MATLAB’s own
functionality to solve 1st order and sets of 1st order differential equations.
MATLAB actually has lots of functions to solve ODEs. The most popular method is ODE45,
which uses a robust algorithm that strategically combines 4th order and 5th order Runga-Kutta
solutions to determine an accurate approximation of a wide variety of common differential
equations.
There are some basic steps to follow when solving ODEs, that are outlined in the following
sections.

43
CHAPTER 4. SOLVING HIGH-ORDER ODES USING MATLAB 44

4.1.1 Defining an ODE Function

First we must define the ODE function in its own m-file. For example, consider the following
m-file (fun1.m) for a first-order differential equation y 0 = −2ty 2 .

function yprime = fun1(t,y)


yprime = -2 * t * y^2;

If you have a system of ODEs, you must define the function as a vector. If you have two 1st
order equations:

y˙1 = y2

y˙2 = y1 − y2

then you would create and m-file (fun2.m) that looks like:

function yprime = fun2(t,y)


yprime = [
y(2) ;
y(1)-y(2)
];

4.1.2 Solving a single ODE Function using ODE45()

The syntax for ODE45 is:

[T,Y] = ODE45( ODEFun, Tspan, y_0)

where T is the independent variable (often time in physical systems), Y is the dependent
variable or vector of independent variables. Tspan = [timeStart, timeStop] is the span of time
of interest. Finally, y 0 is the initial conditions for the system. Remember, you can use any
variable names you like as long as you are consistent!
Consider the following example:

ẋ(t) = sin(xt)

x(0) = 1
0 ≤ t ≤ 10

Create the following .m file called ex1.m:


CHAPTER 4. SOLVING HIGH-ORDER ODES USING MATLAB 45

function xprime=ex1(t,x)
xprime=sin(t*x);

Create an m-file that contains the following commands:

[t,x] = ode45(’ex1’,[0 10], 1);


plot(t,x);
grid on;

Run the m-file and you should see the result:

Problem 4.1 Recreate the above figure except use a time span from 0 to 20 seconds. Turn in
your files and a copy of the figure.

4.1.3 Solving Sets of ODEs using ODE45()

When solving systems of ODEs, we use vectors to organize the system. Consider the system:
" #
y1 y1 (0) = 5.1
~y = where
y2 y2 (0) = 6.7

" # " #
y˙1 cos(y2 ) + sin(t)
~y˙ = =
y˙2 sin(y1 ) − cos(t)

If we are interested in state of the system after 10 seconds, we could have the two m-files:
CHAPTER 4. SOLVING HIGH-ORDER ODES USING MATLAB 46

function yprime=ex2(t,y)
yprime=[
cos(y(2))+sin(t);
sin(y(1))-cos(t)
];

Now y and yprime are both column vectors, so our main m-file may look like.

tspan=[0, 10];
y0=[5.1, 6.7];
[t, y]=ode45(’ex2’, tspan, y0);
plot(t, y);

Problem 4.2 After creating these two m-files, turn in the plot created when you call the main
m-file.

Now that we are familiar enough with ODE45( ) to solve equations, let’s take a quick look at
a traditional mass-spring-damper system.

This system can be modeled with the following equations.

mẍ + cẋ + kx = 0

which we convert to two 1st order equations.

ẋ = v
b k
v̇ = − v− x
m m
CHAPTER 4. SOLVING HIGH-ORDER ODES USING MATLAB 47

which we then write in a generic vector format.


" #
z1
~z =
z2

" # " #
z˙1 z2
~z˙ = = b k
z˙2 − m z2 − m z1

If we are given the initial condition x(0)=.1 m and v(0) = .5 m/s, we could easily set up a
function similar to those above but with the design parameters separated out from the zprime
vector. Consider:

tspan=[0, 10];
y0=[.1, .5];
[t, y]=ode45(’msdfunc’, tspan, y0);
plot(t, y);

and

function zprime=msdfunc(t,z)

m = 4; b = 2; k = 8; %you can do this just like in C++ but not recommended

zprime=[
z(2);
-(b/m)*z(2)-(k/m)*z(1);
];

! You can include any code in the function you like as long as the vector returned by the
function is the derivatives of our state variables. Remember all 1st ODE problems take the
form:

y˙0 = f (x, y1 , y2 , . . . , yn )
..
.
y˙n = f (x, y1 , y2 , . . . , yn )

The vector returned by the function must contain the functions on the right of this general
formulation. Everything else in the function file is flexible. This comes in handy when you
want to play with the design parameters.

Problem 4.3 Turn in the first 10 seconds of the dynamic response for the above system for all
combinations of m=4, b=[2, 5] and k=[4, 8]. (Total of 4 graphs).
CHAPTER 4. SOLVING HIGH-ORDER ODES USING MATLAB 48

4.2 Conclusion

This concludes the final of the four lessons necessary for you to be able to solve dynamic systems
numerically using MATLAB. This is certainly not a comprehensive tutorial, but should allow
students to know use MATLAB to visualize the response of dynamic systems given a set of
initial conditions or input. And our long-term goal is to select that input based on a sound
control strategy. Good luck and your feedback on this tutorial is always welcome.

Вам также может понравиться