Tutorial PDF
Tutorial PDF
December 9, 2009
c Barry G Adams
Contents
1 Quick Tour of the Matlab Environment 2
1.1 Command window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Current directory window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Workspace window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Command history window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Configuring the windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
4 Some Applications 33
4.1 Root finding example for a falling object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
>> pi + 1
ans =
4.1416
>>
Here ans is a variable whose value is the last quantity calculated. If you terminate a command or
statement with a semi-colon the command output is not shown. Try this:
>> pi + 1;
>>
Matlab Tutorial and Reference Page 3 of 40
format short
format compact
The first displays only 4 digits after the decimal point and the second does not leave blank lines in the
output.
If you want to leave blank lines and show the maximum digits in a floating point number you can
use the commands
format long
format loose
Matlab Tutorial and Reference Page 4 of 40
The exponentiation operator is the caret (ˆ) but it associates from left to right (unconventional):
>> 2ˆ3ˆ4
ans =
4096
>> (2ˆ3)ˆ4
ans =
4096
>> -4 ˆ 2
ans =
-16
>>
The last result shows that exponentiation takes precedence over negation. A complete list of opera-
tions can be obtained using either of the help commands
2.1.2 Variables
Variable names begin with a letter which can be followed by 0 or more letters or digits. The underscore
character is considered to be a letter. Each variable can hold a value of any type. For example try the
following statements.
>> x = ’hello’
x =
hello
>> x = 3
x =
3
>> y = 4
y =
4
>> z = xˆ2 + yˆ2
z =
25
>>
Note how variable x first holds a string value and then holds a numeric value.
If you look at the workspace window you will see that x, y and z appear as workspace variables.
To remove the variable x from the workspace use the command
>> clear x
To see the value of any variable, say z, simply type its name and press enter:
>> z
z =
5
>>
If you try to access a variable that was removed you get an error message:
>> x
??? Undefined function or variable ’x’.
Matlab Tutorial and Reference Page 6 of 40
You can also use the help browser from the main Help menu. Try these examples noting that log, not
ln, is the logarithm to base e.
>> x = 3;
>> y = 4;
>> z = sqrt(xˆ2 + yˆ2)
z =
5
>> sin(pi/2)ˆ2 + cos(pi/2)ˆ2
ans =
1
>> log(1.12)
ans =
0.1133
>> exp(1.0)
ans =
2.7183
>>
Here pi is the value of π and there is also e for the value of e1 . Angles for trigonometric functions
must be in radians and the inverse trigonometric functions return an angle in radians. Sometimes it is
more convenient to use angles in degrees. M ATLAB provides degree versions sind(x) and similarly
for the other 5 trigonometric functions. For the inverse functions the value returned from asind(x)
is in degrees. Try the following statements.
>> sind(90)
ans =
1
>> asind(1)
ans =
90
>>
Matlab Tutorial and Reference Page 7 of 40
where v m/s is the velocity of a water wave, d = 50 m is the depth of water without the wave,
L = 100 m is the wave length of the wave, and g = 9.81 m/s2 is the acceleration due to gravity.
>> g = 9.81;
>> L = 100;
>> d = 50;
>> v = sqrt( (g*L)/(2*pi)*tanh(2*pi*d/L))
v =
12.4719
>>
v2 sin 2θ
h=
2g
where h m is the maximum height of a projectile moving in a vertical plane at an angle θ = 50 degrees
from the horizontal and having speed v = 20 m/s, and g = 9.81 m/s2 is the acceleration due to gravity.
>> g = 9.81;
>> v = 20;
>> theta = 50*pi/180;
>> h = vˆ2*sin(2*theta)/(2*g)
h =
20.0776
>>
To convert from degrees to radians we have multiplied 50 by π/180. As mentioned earlier MATLAB
has the usual trig functions sin, cos, and tan for angles in radians and sind, cosd, and tand for
angles in degrees. Here is the previous calculation using sind
>> g = 9.81;
>> v = 20;
>> theta = 50;
>> h = vˆ2*sind(2*theta)/(2*g)
h =
20.0776
>>
Matlab Tutorial and Reference Page 8 of 40
where f-name is the name of the function, var-name is the name of the independent variable and
expression is the expression defining the function in terms of the independent variable. The function
name is also called a function handle.
Example The formula 49(t + 5e−t/5 ) − 245 is an expression that defines a function of t. In MATLAB
this function can be expressed as the anonymous function of t.
>> f(1.5)
ans =
10.0005
>> f(11)
ans =
321.1468
It is also possible to define anonymous functions of more than one variable. For example, the formula
s
gL 2πd
v= tanh
2π L
It is also possible to have anonymous functions inside other anonymous functions. For example,
if f (x) = x2 , g(x) = 3x, the composition is h(x) = ( f ◦ g)(x) = f (g(x)). This can be expressed in
MATLAB as
>> x = [6 5 4]
x =
6 5 4
>> x = [6,5,4]
x =
6 5 4
Each element has an index and indices always begin at 1. Thus x has 3 elements. Parentheses are
used to access an individual element using its index. Thus, the three elements of x can be obtained as
x(1), x(2), and x(3). The following statement accesses the second element of the vector x.
>> x(2)
ans =
5
The following statements show that the elements of a vector can also be changed.
>> x = [6 5 4]
x =
6 5 4
>> x(2) = 99
x =
6 99 4
Similarly column vectors can be expressed in two ways. The first way is to use a semi-colon to
terminate each row and the second way is to press the enter key at the end of each row. Try the
following statements.
>> x = [6;5;4]
x =
6
5
4
Matlab Tutorial and Reference Page 10 of 40
>> x = [
6
5
4
]
x =
6
5
4
>>
Length of a vector The number of elements in a row or column vector is given by the length
function. Try the following statements.
>> x = [6,5,4]
x =
6 5 4
>> length(x)
ans =
3
Constructing zero vectors The zeros function can be used to construct vectors and matrices whose
elements are initialized to zero: The first argument of the zeros function gives the number of rows
and the second argument gives the number of columns.
>> x = zeros(1,4)
x =
0 0 0 0
>> y = zeros(4,1)
y =
0
0
0
0
>>
Arithmetic sequence vectors These important sequences can be constructed using the colon oper-
ator. The expression a:b gives a row vector whose elements go from a up to b inclusive in steps of 1,
the expression a:c:b creates a vector whose elements go from a up to b inclusive in steps of c if c is
positive, or from a down to b in steps of |c| if c is negative. Try the following examples.
>> x = 1:4
Matlab Tutorial and Reference Page 11 of 40
x =
1 2 3 4
>> y = 1:2:10
y =
1 3 5 7 9
>> z = 10:-1:2
z =
10 9 8 7 6 5 4 3 2
>>
The linspace function This function can be used to divide an interval into equally spaced subinter-
vals and put the results into a row vector. For example linspace(0,1,11) divides the interval 0 to
1 using 11 points. The width of each subinterval is 0.1. If the third argument is not present then 100
points are used. Try the following statements (some output is omitted to save space).
>> x1 = linspace(0,1,11)
x1 =
Columns 1 through 6
0 0.1000 0.2000 0.3000 0.4000 0.5000
Columns 7 through 11
0.6000 0.7000 0.8000 0.9000 1.0000
>> x2 = linspace(0,1)
x2 =
Columns 1 through 6
0 0.0101 0.0202 0.0303 0.0404 0.0505
Columns 7 through 12
0.0606 0.0707 0.0808 0.0909 0.1010 0.1111
Columns 13 through 18
0.1212 0.1313 0.1414 0.1515 0.1616 0.1717
.
.
.
Columns 91 through 96
0.9091 0.9192 0.9293 0.9394 0.9495 0.9596
Columns 97 through 100
0.9697 0.9798 0.9899 1.0000
>>
Subvectors The colon operator can be used to make a subvector. Try the following statements.
>> x = [5,4,3,2]
Matlab Tutorial and Reference Page 12 of 40
x =
5 4 3 2
>> y = x(2:3)
y =
4 3
>> y(1)
ans =
4
>>
Here 2:3 is used to make a vector y from the second and third elements of the vector x. The special
value end refers to the last element of a vector. Try the following statements.
>> x = [5 6 7 3 4 8 9]
x =
5 6 7 3 4 8 9
>> y = x(4:end)
y =
3 4 8 9
>>
Transpose of a vector A row vector can be converted to a corresponding column vector and vice
versa using the transpose operation which is the single quote character. Try the following statements:
>> x = [6,5,4]
x =
6 5 4
>> y = x’
y =
6
5
4
>>
Vector operations from linear algebra In linear algebra vectors of the same length and type (row
or column) can be added and subtracted and multiplied by a scalar. This is easily done in MATLAB.
We illustrate the operations using row vectors but the same rules also apply to column vectors. Try
the following statements.
Matlab Tutorial and Reference Page 13 of 40
>> x = [6,5,3];
>> y = [2,4,3];
>> x + y
ans =
8 9 6
>> x - y
ans =
4 1 0
>> 2*x + 4*y
ans =
20 26 18
>>
Adding scalars and vectors In linear algebra it is not possible to add or subtract a scalar and a
vector but this is possible and useful in MATLAB. Such operations are called array operations or
element-by-element operations as opposed to matrix operations. For example 3 + x is obtained by
adding 3 to each element of x, x - 1 is obtained by subtracting 1 from each element of x, and 2 - x
is obtained by subtracting each element of x from 2. Try the following statements.
>> x = [6,5,4];
>> 3 + x
ans =
9 8 7
>> x - 1
ans =
5 4 3
>> 2 - x
ans =
-4 -3 -2
>>
Element by element exponentiation Exponentiation of each element in a vector can be done using
an element-by-element version of the exponentiation operator ˆ, denoted by .ˆ, and pronounced “dot
hat”. Try the following statements.
>> x = [6,5,4]
x =
6 5 4
>> xˆ2
??? Error using ==> mpower
Matrix must be square.
Matlab Tutorial and Reference Page 14 of 40
>> x.ˆ2
ans =
36 25 16
>>
This shows why the operator ˆ cannot be used. It is a matrix operation so xˆ2 is trying to multiply x
by itself and this operation is only defined for square matrices (n × n) matrices. Therefore we need a
new operator to do element by element exponentiation (don’t put a space between . and ˆ).
Example The square of the length of a vector x = [x1 , x2 , . . . , xn ] is given by x12 + x22 + · · · xn2 . This
can be done in MATLAB two ways. Try the following
>> x = [6,5,4]
x =
6 5 4
>> x * x’
ans =
77
>> sum(x.ˆ2)
ans =
77
>>
Here we multiply x by its transpose x’. This is a matrix multiplication of a 1 × 3 column vector and a
3 × 1 row vector to give a 1 × 1 scalar to get the sum of squares, This can also be done using the sum
function which adds together all the elements of a vector.
C =
6 7 2
9 2 3
>>
The size function The size function can be used to determine the number of rows and columns in
a matrix. This function returns the row and column dimensions as a two element row vector. Try the
following statements.
Subscript notation To reference the element of A in row i and column j the notation A(i,j) is
used. Try the following statements.
Submatrices and the colon operator The colon operator can be used to refer to individual rows
and columns and submatrices. Try the following statements.
2
6
>> B2 = B(1:2,1:2)
B2 =
6 9
6 4
>>
Here A(2,:) refers to all columns of row 2, A(:,2) refers to all rows of column 2, and B(1:2,1:2)
refers to the first two rows and columns of B which is just the top left 2 × 2 matrix.
Scalar multiplication To multiply a matrix by 3 you multiply each element of the matrix by 3. Try
the statement
>> A = [1,2,9; 3,6,8];
>> 3*A
ans =
3 6 27
9 18 24
>>
Matrix multiplication Two matrices A and B can be multiplied to give the product AB only if the
number of columns of A is the same as the number of rows of B. In MATLAB the matrix product is
given by A*B. Try the following statements using the matrices defined above.
Here B*A does not exist since B has 3 columns and A has only 2 rows.
Solving a linear system An n × n system of linear equations has the form Ax = b where A is the
n × n coefficient matrix, b is the right hand side column vector and x is the column vector for the
solution.
In MATLAB the backslash operator is used to solve the linear system. For example try the following
system.
2.5 Vectorization
Instead of writing loops to process vectors and matrices one element at a time it is often possible to
work directly with the vectors and matrices, avoiding loops altogether. This is called vectorization.
Example As a simple example suppose we have the five element vector d = [0, 30, 45, 60, 90] of
angles in degrees and we want to convert it to a vector r with angles in radians by multiplying each
element of d by π/180. Then we want to convert r to a vector y whose elements are the sines of these
angles. The components of the vectors r and y are given for k = 1, 2, . . . , 5 by
rk = π dk /180,
yk = sin(rk )
Then we would need to use a loop to compute y1 , y2 , . . . , y5 . Try the following statements that
compute the vector r and y using a for loop over the values k from 1 to 5:
>> d = [0,30,45,60,90]
d =
0 30 45 60 90
>> for k = 1:5
r(k) = d(k)*pi/180;
y(k) = sin(r(k));
end
>> r
r =
0 0.5236 0.7854 1.0472 1.5708
>> y
y =
0 0.5000 0.7071 0.8660 1.0000
The vectorized way to do this has no loops:
>> d = [0,30,45,60,90]
d =
0 30 45 60 90
>> r = d*pi/180
r =
0 0.5236 0.7854 1.0472 1.5708
>> y = sin(r)
y =
0 0.5000 0.7071 0.8660 1.0000
Here the factor pi/180 automatically multiplies every element of the vector d to give the vector r.
Then the sin function is designed to work on vectors in the same way by taking the sine of each
element and producing a vector of sines.
If we don’t need the vector r we can obtain y in one statement
Matlab Tutorial and Reference Page 20 of 40
>> y = sin(d*pi/180)
y =
0 0.5000 0.7071 0.8660 1.0000
>>
Example: Displaying a table of values With vectorization it is easy to produce a table of values
of a function. Suppose we want to compute a table of the sine function on the interval 0 to 1 in steps
of 0.1. First we use the colon operator to construct the vector x of points. Then we apply the sine
function to this vector to get a vector y of function values. Then we construct a two column table
(matrix) by transposing the row vectors x and y to column vectors x’ and y’ and concatenating them
together using [x’,y’]. Try the following statements to see the results
>> x = 0:0.1:1;
>> y = sin(x);
>> [x’,y’]
ans =
0 0
0.1000 0.0998
0.2000 0.1987
0.3000 0.2955
0.4000 0.3894
0.5000 0.4794
0.6000 0.5646
0.7000 0.6442
0.8000 0.7174
0.9000 0.7833
1.0000 0.8415
>>
Example: Vectorized anonymous function Try the following statement which defines the func-
tion:
1 1
y= + −6
(x − 0.2) + 0.01 (x − 0.8)2 + 0.04
2
Note how vectorization is used in this function. Let’s trace what happens. First 0.2 is subtracted from
each element of the vector x. Then each element of the resulting vector is squared, using .ˆ2. Then
0.01 is added to each element of the resulting vector. Then ./ is applied to 1 and this vector. Call the
result x1.
Then for the second term 0.8 is subtracted from each element of the vector x. Then each element
of the resulting vector is squared, using .ˆ2. Then 0.04 is added to each element of the resulting
vector. Then ./ is applied to 1 and this vector. Call the result x2.
Matlab Tutorial and Reference Page 21 of 40
Finally x1 and x2 are added and 6 is subtracted from each element of the resulting vector to get
the final vector.
fplot(func, [xmin,xmax])
fplot(func, [xmin,xmax,ymin,ymax])
where func is a function handle (reference to a function). In the first form xmin and xmax are the
horizontal limits for the graph. In the second form the vertical limits are also specified
Example: plotting trig functions To plot one of the built-in functions you need to prefix the func-
tion name with the @ character. This creates a function handle. Try the following plots (WARNING:
plot windows have a nasty habit of hiding behind other windows, so if you don’t see your plot window,
its probably hiding).
Since the tan function has vertical asymptotes it is necessary to specify vertical limits.
100
90
80
70
60
50
40
30
20
10
0
0 0.2 0.4 0.6 0.8 1
Note that in the call to the fplot function it is not necessary to use the ampersand character since the
right hand side of the definition of y already has the ampersand. In other words f is already a function
handle. On the other hand, when using built-in functions such as sin it is necessary to use @sin to
get a function handle.
plot(x,y)
where x is the vector of points to use for the x-axis and y is the vector of points for the y-axis. The
points in the plane are given by (xk , yk ) for k = 1, . . . , n. The plot function joins the points (x1 , y1 ),
(x2 , y2 ), . . . , (xn , yn ) by straight line segments. It follows that the more points you use the smoother
the graph. Try the following statements, and be sure to terminate the first two statements with a
semi-colon.
>> x = linspace(0,2*pi,100);
>> y = tan(x);
>> plot(x,y)
>> axis([0,2*pi,-5,5])
>> xlabel(’x’)
>> ylabel(’y’)
>> title(’Plot of y = tan x’)
Matlab Tutorial and Reference Page 23 of 40
We can also use plot for a table of values not obtained from a function. Try the following statements
which generate random values in the range 0 to 1.
>> x = linspace(0,1,100);
>> y = rand(1,100);
>> plot(x,y)
Plot of y = tan x
5 1
4 0.9
3 0.8
2 0.7
1 0.6
0 0.5
y
−1 0.4
−2 0.3
−3 0.2
−4 0.1
−5 0
0 1 2 3 4 5 6 0 0.2 0.4 0.6 0.8 1
x
x = linspace(0,2*pi,1000);
y1 = sin(x);
y2 = cos(x);
plot(x,y1,’-’, x,y2,’-’)
axis([0,2*pi,-1,1])
0.8
0.6
0.4
0.2
−0.2
−0.4
−0.6
−0.8
−1
0 1 2 3 4 5 6
Matlab Tutorial and Reference Page 24 of 40
Here each graph will be drawn with a solid line as indicated by the hyphens. They will have different
colors. To plot cos x using a dashed line replace the second hyphen by two hyphens.
• Script M-Files: They contain MATLAB statements that can be executed by typing the script
name in the command window (without the file extension). M ATLAB executes the statements
as though they were entered one by one in the command window.
• Function M-files: They contain MATLAB functions that are executed in the same way as the
built-in functions and function M-files.
It is important to change the current directory, if necessary, to the one containing your M-files. M AT-
LAB will look there for scripts we are going to write.
Enter the script Now enter the following script (if you hate typing and you are using the online
version of this PDF file you can cut and paste it from the PDF file to the MATLAB editor).
d = b*b - 4*a*c;
Matlab Tutorial and Reference Page 25 of 40
if d > 0
root1 = (-b + sqrt(d)) / (2*a);
root2 = (-b - sqrt(d)) / (2*a);
disp(’Real unequal roots’);
disp(root1);
disp(root2);
elseif d < 0
root_real = -b / (2*a);
root_imag = sqrt(abs(d));
disp(’Complex roots’);
disp(complex(root_real, root_imag));
disp(complex(root_real, -root_imag));
else
root = -b / (2*a);
disp(’Real equal roots’);
disp(root);
end
• Make sure you terminate lines by semi-colons if you don’t want to see their output.
• The input command is used to prompt for and enter 3 floating point numbers. To enter a string
use a statement such as name = input(’Enter your name ’, ’s’);.
• The disp function is used to display an array or a string, a string in our case. The display occurs
whether or not the statement is terminated by a semi-colon.
• M ATLAB can do arithmetic on complex numbers. The complex function takes two arguments,
for the real and imaginary parts of the complex number and constructs a complex number from
them. Then disp displays this complex number.
Although not illustrated in this example script, if you want to break a long line over several lines it is
necessary to use ... at the end of a line to be continued. For example, the two lines defining root1
and root2 could be expressed as
root1 = ...
(-b + sqrt(d)) / (2*a);
root2 = ...
(-b - sqrt(d)) / (2*a);
Matlab Tutorial and Reference Page 26 of 40
Running the script To run the script enter its name, without the file extension, in the command
window (if you get a “not found” error you have saved the file in the wrong directory or the current
directory has not been set to the directory containing your file). Try the following
>> quad_script
Enter coeff of xˆ2 1
Enter coeff of x 1
Enter constant coeff 1
Complex roots
-0.5000 + 1.7321i
-0.5000 - 1.7321i
>> quad_script
Enter coeff of xˆ2 1
Enter coeff of x 2
Enter constant coeff 1
Real equal roots
-1
>> quad_script
Enter coeff of xˆ2 1
Enter coeff of x 2
Enter constant coeff -3
Real unequal roots
1
-3
x = a/2;
for k = 1:max_iter
x = 0.5*(x + a/x);
disp(x);
end
Matlab Tutorial and Reference Page 27 of 40
Note that we have squared the result as a check. The for loop uses the colon operator to define the
range of the loop index. A more general range could be specified by the arithmetic sequence a:c:b
which goes from a up to b in steps of c if c > 0 and from a down to b in steps of |c| if c < 0.
Using a while loop The following while loop version is equivalent. Try it and save it in the file
sq root2.m:
% Simple algorithm for square roots
% This version uses a while loop
x = a/2;
k = 1;
while k <= max_iter
x = 0.5*(x + a/x);
disp(x);
k = k + 1; % don’t forget this
end
A third version We can write a version of the square root algorithm that terminates if a given
tolerance (maximum error) is obtained or if a maximum number of iterations is exceeded. We will
stop the algorithm if the relative error of successive iterations is met. This means that we stop iterating
if
xk − xk−1
< tol
k x
Matlab Tutorial and Reference Page 28 of 40
x_old = a/2;
for k = 1:max_iter
x_old = x_new;
end
if k == max_iter
fprintf(’Failure to converge in %d iterations\n’, max_iter)
end
Note that the for loop makes sure the loop is not infinite and the break statement causes the loop to
exit if the given tolerance is met. When the loop exits we can check whether the break occurred.
This script also illustrates the fprintf statement. See help on sprintf and fprintf. In our
case the string is displayed with the format code %d replaced by the value of max_iter. Here is some
output in the command window.
Testing the factorial function In the command window the fact function can be executed as fol-
lows
>> fact(10)
ans =
3628800
>> fact(12)
ans =
479001600
>> fact(13)
ans =
6.2270e+009
Note that 12 is the last value of n whose factorial can be computed exactly using the MATLAB double
precision arithmetic. The factorial function is a built-in function with name factorial.
c1 = m*g/k;
c2 = m/k;
x0 = 0;
v0 = 0;
v = c1 + (v0 - c1)*exp(-t/c2);
x = x0 + c1*t + c2*(v0 - c1)*(1 - exp(-t/c2));
end
The falling_object function is also a vectorized function so the value of t can be supplied as a
vector. For example try
>> t = 10:0.1:12;
>> [x,v] = falling_object(9.81, 10, 2, t)
x =
Columns 1 through 6
278.4410 282.6888 286.9495 291.2231 295.5091 299.8074
Columns 7 through 12
304.1178 308.4399 312.7735 317.1184 321.4745 325.8414
Columns 13 through 18
330.2189 334.6070 339.0052 343.4135 347.8316 352.2594
Columns 19 through 21
356.6966 361.1430 365.5986
v =
Columns 1 through 6
42.4118 42.5432 42.6721 42.7984 42.9222 43.0435
Columns 7 through 12
43.1624 43.2790 43.3933 43.5053 43.6151 43.7227
Columns 13 through 18
Matlab Tutorial and Reference Page 32 of 40
>> [t’,x’,v’]
ans =
10.0000 278.4410 42.4118
10.1000 282.6888 42.5432
10.2000 286.9495 42.6721
10.3000 291.2231 42.7984
10.4000 295.5091 42.9222
10.5000 299.8074 43.0435
10.6000 304.1178 43.1624
10.7000 308.4399 43.2790
10.8000 312.7735 43.3933
10.9000 317.1184 43.5053
11.0000 321.4745 43.6151
11.1000 325.8414 43.7227
11.2000 330.2189 43.8282
11.3000 334.6070 43.9316
11.4000 339.0052 44.0330
11.5000 343.4135 44.1323
11.6000 347.8316 44.2297
11.7000 352.2594 44.3251
11.8000 356.6966 44.4187
11.9000 361.1430 44.5104
12.0000 365.5986 44.6003
>>
Note that an initial height of 300 metres is obtained for t ≈ 10.5 seconds
4 S OME A PPLICATIONS
4.1 Root finding example for a falling object
Drop an object with a mass of 10 kg from the top of a 300 m high building. Assume that air resistance
is −kv where v m/s is the velocity, k = 2 kg/s is the air resistance and g = 9.81 is the acceleration
due to gravity.
How long does it take for the object to reach the ground? What will be the velocity at that time?
Assuming that the positive direction is downward it can be shown that the differential equation for
the velocity is (from Newton’s second law)
dv
m = mg − kv
dt
This equation can be solved to give the velocity v and the position x below the top of the building:
The object hits the ground when x(t) = 300 so we need to find this value of t. Note the x(t) is almost
a linear function since e−t/5 → 0 very fast as t → ∞. If we neglect the exponential term we get the
linear function
The solution of xlinear (t) = 300 is given by t = (300 + 245.25)/49.05 = 11.1162. We can use this as
an initial guess to find the root of x(t) = 300. The following MATLAB statements define x and v as
anonymous functions
The root finding problem is x(t) − 300 = 0 so we look for a zero of the function
>> xt_root = @(t) xt(t) - 300;
We can use the linear approximation t = 11.1162 and plot the function xt_root on the interval from
t = 10 to t = 12 to verify that there is a root in this interval:
>> fplot(xt_root,[10,12])
The MATLAB root finding function fzero can be used to find the root when x(t) − 300 = 0 in the
interval from 10 to 12 using
5.1 Commands
clc Clear the command window
clear x Clear (remove) variable x from workspace
clear all Clear all variables from workspace
doc Display documentation
help Displays help text in the Command window
helpwin Displays help text in separate window
who gives a list of current variables
whos longer version of who