Programming Mathematics Using MATLAB - Sanet.st
Programming Mathematics Using MATLAB - Sanet.st
MATHEMATICS
USING MATLAB®
PROGRAMMING
MATHEMATICS USING
MATLAB®
LISA A. OBERBROECKLING
Department of Mathematics and Statistics
Loyola University Maryland
Baltimore, MD, United States
Academic Press is an imprint of Elsevier
125 London Wall, London EC2Y 5AS, United Kingdom
525 B Street, Suite 1650, San Diego, CA 92101, United States
50 Hampshire Street, 5th Floor, Cambridge, MA 02139, United States
The Boulevard, Langford Lane, Kidlington, Oxford OX5 1GB, United Kingdom
Copyright © 2021 Elsevier Inc. All rights reserved.
ISBN: 978-0-12-817799-0
Preface xiii
Introduction xv
Part 1. MATLAB®
1. Introduction to MATLAB® 3
1.1. Basic MATLAB® information 3
1.1.1. Starting MATLAB 3
1.1.2. Good commands to know 3
1.2. Basic mathematics 4
1.2.1. Built-in mathematical functions 5
1.2.2. Precedence rules 6
1.2.3. Formats 8
1.3. Variables 9
1.4. Diaries and script files 10
1.5. Exercises 12
3. Plotting in MATLAB® 33
3.1. Basic 2D plots 33
3.2. Bad domain examples 34
3.3. Axis settings 35
3.4. Multiple plots 40
3.5. Color, line, and marker modifications 43
3.5.1. Clf/close all 46
3.5.2. Subplots 46
3.6. Other 2D plots 49
3.6.1. Parametric curves 49
3.6.2. Polar curves 50
3.7. Exercises 52
4. Three-Dimensional Plots 59
4.1. Vector functions or space curves 59
vii
viii Contents
5. Functions 83
5.1. The lookfor and help commands 83
5.2. File format 84
5.3. Function examples 86
5.3.1. Basic function examples 86
5.3.2. More function examples – multiple inputs 86
5.3.3. Multiple outputs 87
5.3.4. Bad examples 89
5.4. Exercises 90
6. Control Flow 93
6.1. Relational and logical operators 93
6.2. If statements 97
6.3. Switch/case 99
6.4. Use of characteristic functions 99
6.5. For loops 100
6.6. While loops 102
6.7. Useful commands break, continue, return, and error 103
6.8. Optional inputs and outputs of functions 104
6.9. Exercises 107
References 271
Index 273
Preface
This book started in 2004 when I started to use MATLAB® in my courses at Loyola
University Maryland. I started including a few MATLAB projects within the intro-
duction to linear algebra and multivariable calculus courses. I also taught a one-credit
MATLAB course that was required of every mathematics major. Later the course was
changed to a three-credit course. I expanded the previous assignments and added some
others. The class notes and assignments from over the years have expanded into this
book.
My philosophy has always been to use MATLAB to practice basic programming skills
with mathematics topics students had seen previously, such as numerical integration, and
topics they likely had not seen such as fractals. Visualizing mathematics has always been
important.
Supplements
Student companion site: Please visit https://www.elsevier.com/books-and-journals/
book-companion/9780128177990
Instructor-only site: Qualified instructors can register and access teaching materials
at https://textbooks.elsevier.com/web/Manuals.aspx?isbn=9780128177990
xiii
Introduction
The goal of the course and thus book is to introduce MATLAB® and to practice basic
programming techniques. There is a lot more to MATLAB than what is covered in this
book. Most students have already had some programming experience in another lan-
guage before taking the course this book has stemmed from, although it is not necessary.
On completion of the course/book, one should be familiar enough with MATLAB to
explore more complicated features and commands. Deepening your understanding of
mathematics and learning new topics are bonuses!
xv
CHAPTER 1
Introduction to MATLAB®
1.1. Basic MATLAB® information
1.1.1 Starting MATLAB
MATLAB has many different windows or panels, the first three of which are on the
main screen by default (see Table 1.1).
You can always modify the layout of the panels including “docking” or “undock-
ing” them, in the “Home” view, select “Layout” from the menu and the top item is
“Default.” In order to use MATLAB successfully, you should pay attention to the Cur-
rent Folder. Otherwise, MATLAB may not be able to save and run your programs/files
successfully.
clear/close named figures, etc. such as clf(2) and close(2) that will clear or close
Figure 2, respectively.
• format Sends the output display back to the default format. The command format
compact will not have as much white space (blank lines) between subsequent
commands and output.
• exit or quit Quit MATLAB. You can also quit/exit MATLAB by using the
MENU option under “File” or the usual close application icon within a Mac or
Windows environment.
ans =
>> 10/3
ans =
3.3333
>> 10\3
ans =
0.3000
Thus the forward slash is our usual division, “3 divided by 2” while the backslash is “3
divided into 2.” The need for both of these become more apparent when working with
matrices.
“Dot” operations or component-wise operations are useful and/or necessary for
use with vectors and matrices (discussed in Section 2.4). These are considered “array
arithmetic operations” and are carried out element or component-wise.
MATLAB does NUMERICAL, rather than algebraic computations, as seen below.
Think about what is expected versus what is given as the answer to the subraction
calculation.
>> asin(1/2)
ans =
0.5236
ans =
-1.1102e-16
>> mod(10,3)
ans =
1
6 Programming Mathematics Using MATLAB®
>> rem(10,3)
ans =
>> mod(10,-3)
ans =
-2
>> rem(10,-3)
ans =
>> mod(10,0)
ans =
10
>> rem(10,0)
ans =
NaN
If you have a long calculation/expression, you can continue on the next line in
the command window or within a MATLAB file with the ellipses or continuation
operator. Note when the ellipses work with/without spaces:
ans =
-89
ans =
-89
>> 1+2*3-12^2/3*...
2
8 Programming Mathematics Using MATLAB®
ans =
-89
>> 1+2*3-12^2/3...
1+2*3-12^2/3...
|
Error: Unexpected MATLAB operator.
1.2.3 Formats
As mentioned above, the format command returns the format back to the default
format, which is the same as format short. Generally speaking, this will display a
number up to four decimal places, while format long will display 15. In scientific
notation, this amounts to five and 16 significant digits, respectively. See Table 1.4.
>> pi
ans =
3.1416
ans =
3.141592653589793
There are other built-in formats, including how numbers in scientific notation are dis-
played. See help format for more examples.
Another useful command is format compact and format loose (default). This
will change how the output is displayed.
>> pi
ans =
3.1416
>> pi
ans =
3.1416
>>
The subsequent commands shown in this text will use format compact (see Table 1.4).
1.3. Variables
The format for a variable assignment is as follows:
Variable name = Numerical value or computable expression
Some conventions:
• The = is the assignment operator which assigns a value to a variable.
• Left-hand side can include only one variable name.
• Right-hand side can be a number or an expression made up of numbers, functions,
and/or variables previously assigned numerical values.
• Variables must begin with a letter.
• Press the Enter/Return key to make the assignment.
• The variable ans is the value of the last expression that is not assigned.
• Be careful with variable names. For example, do not name a variable help or sin.
• Variable names are case sensitive; thus A is not the same as a.
Remember:
• Use semicolon (;) to suppress screen output.
• Multiple commands can be typed on one line by typing a comma (,) between them
if they are not already ended with a semicolon (;).
10 Programming Mathematics Using MATLAB®
√
Example 1.3.1. Assign the number 3 to variable a and 4 to variable b. Print a2 + b2
and assign the solution to the variable c.
Notice in the above example, you do not need spaces around the “=” for variable
assignments but you may use them for aesthetic reasons.
>> x = pi/5;
>> LHS = (cos(x/2))^2, RHS = (tan(x)+sin(x))/(2*tan(x))
LHS =
0.9045
RHS =
0.9045
>> format long
>> LHS, RHS
LHS =
0.904508497187474
RHS =
0.904508497187474
>> LHS-RHS
ans =
-1.110223024625157e-16
more than once (within the same current folder), it will continue to APPEND to the
file.
For example, the commands above will generate the following text in the file “file-
name”:
1+1
ans =
2
diary off
3^2
ans =
9
diary
Script files, or m-files, are extremely useful for running and rerunning code. You
may be required to turn in script files for your assignments.
• Script files are ASCII files (plain text files) with extension .m; thus they are also
called m-files. These are basically batch files.
• When you run a SCRIPT file, MATLAB executes each line as if you typed each
line into the command window.
• Script files are very useful; you can edit them, save them, execute them many times
and “tweak” them to experiment with commands.
• The MATLAB editor window is the best way to create and edit script files.
• To avoid extraneous output to the command window, put “;” after variable assign-
ments or intermediate calculations.
• Comments within MATLAB files begin with the percent symbol (%).
Running script files:
There are many ways to run an m-file of name filename.m. First, you must MAKE
SURE CURRENT FOLDER IS CORRECT!
12 Programming Mathematics Using MATLAB®
1. >> filename
2. >> run filename
3. >> run('filename')
4. Within the Editor tab, chose run...
1.5. Exercises
1. Basic calculations Use MATLAB to do the following calculations. Be careful! The
following are displayed using regular mathematical notation; you need to figure out
what MATLAB functions are needed.
7 .753 292 644/3
(a) (2.4)(64 ) + 8 , (b) + + 20 · 9−3 ,
16 2 − 225 5 11
(c) cos(360), (d) cos(360◦ ),
(k) From the above calculations, do you see anything surprising with the answers?
1 √
(l) Calculate (−x) 4 and 4 −x. What are the differences?
(m) Calculate (−8)2/3 and 82/3 on paper using your exponent rules. Now do the
calculations within MATLAB, Excel, Google.com, WolframAlpha.com, and
a scientific or graphing calculator (specifying what model you have used).
What are the differences, if there are any?
7. Calculator precision √
(a) Within an Excel spreadsheet or Google Sheet, calculate 12 178212 + 184112
using exponential notation for the calculations. Write your answer clearly.
(b) Rewrite the above expression with your answer to part (a) into an equation
and algebraically simplify the equation so there are no radicals or rational
exponents. √
(c) Now calculate 12 178212 + 184112 using MATLAB.
(d) Compare the left-hand side and right-hand side of the equation you get in
part (b) by subtraction within MATLAB, using format long).
14 Programming Mathematics Using MATLAB®
(e) Calculate “3 quadrillion and 18 minus 3 quadrillion and 14” in your head
and write it down. Now translate this into mathematics so you can calculate
it within Google.com, Excel, and MATLAB. (You may need to look up how
many zeros you will need!) Compare your answers in a table.
(f) Do the same with 2.000000000000018 − 2.000000000000014.
8. Ambiguities with notation. Define variables with the assignments x = 10 and
y = π/4. Calculate the following within MATLAB. You may have to adjust from
mathematical notation to correct MATLAB notation. Make sure you are using the
default format!
(a) cos y, (b) cos y2 , (c) cos(y2 ), (d) cos2 y, (e) (cos y)2 ,
(j) Redo part (g) and then use the MATLAB variable ans to calculate
cos−1 (x/20)
.
4y
(k) Are any of the above calculations ambiguous in how they are written (which
ones and why)? What could be done to make the calculations clearer to the
person performing/entering the calculations?
9. Exploring rem and div. It is common to use either of the functions mod or rem
to tell whether positive integers are even or odd, among other uses. We will explore
the differences and similarities of these functions.
(a) Here is another simple use for these functions. You are given a list of 10-digit
numbers. You would like to only use the last seven digits of these numbers (for
example, for display purposes). Use both the mod or rem functions to easily
get the last seven digits of the number 4108675309. Do you see a difference
in their use for this?
(b) Use the same commands on the number -4108675309. Do you see a differ-
ence? Explain in your own words what you think is the difference between
the mod and rem functions. Is there a difference when using these functions
to tell whether any integer is even or odd?
(c) Can you come up with a way, using MATLAB functions such as mod, rem,
round, ceil, fix, etc. to capture the “area code” (first three digits) of
4108675309? Experiment with at least two phone numbers with different
area codes.
(d) What about capturing the “central office” part of the number (867)? Do it
for 4108675309 and 4106172000.
CHAPTER 2
>> y = [4;5;6]
y =
4
5
6
There are ways to define vectors without having to enter every element. The two most
common ways are to define constant spaced and equally spaced (linearly spaced) vectors.
variablename = [m: q : n]
1 3 5
z =
1 4 7 10 13 16 19 22 25
w =
1 4 7 10 13 16 19 22
Notice in the vectors y and w above that the last number (n) may not actually be a value
in the vector if the increment (q) is such that it will not occur based on the starting
value (m).
One can also increment backwards with a negative increment value.
Notice that both the values m and n are elements in the vector.
There is also a command logspace that is also useful for plotting (among other
things). The command logspace(a,b) will generate a row vector of 50 logarithmically
spaced points from 10a and 10b . If b is pi, then the points are between 10a and π .
variablename = logspace(a,b)
variablename = logspace(a,b,q)
Just as in linspace, you can specify the number of elements in the vector by stating
the value q.
Vectors and Matrices (Arrays) 17
>> logspace(0,5,6)
ans =
1 10 100 1000 10000 100000
>> logspace(5,1,5)
ans =
100000 10000 1000 100 10
>> linspace(1,pi,4)
ans =
1.0000 1.7139 2.4277 3.1416
>> logspace(0,pi,4)
ans =
1.0000 1.4646 2.1450 3.1416
>> logspace(2,pi,3)
ans =
100.0000 17.7245 3.1416
2x + 3y + z = 4,
x − 5y + 3z = 3,
4x − 2y + 3z = 2.
The format for defining matrices expands on the format for defining row and column
vectors; spaces or commas between elements within a row with semicolons between
rows.
variable = [1st row ; 2nd row ; ... ; last row]
You can also use vectors of the same size to be rows (or columns) of a matrix, as we do
to define the matrix B below.
Elements of vectors
• v(k) picks the kth element of v.
• v(m:n) picks the mth through the nth elements of v.
>> v = linspace(0,1,5)
v =
0 0.2500 0.5000 0.7500 1.0000
>> v(3)
ans =
0.5000
>> v(2:4)
ans =
0.2500 0.5000 0.7500
Elements of matrices
• A(m,n) picks the (m, n)th element (element in the mth row, nth column) of the
matrix A.
• A(m:n, p:q) gives the submatrix from the elements (m : n) × (p : q)
• A(m:n, :) gives rows m through n, and every column of A
Vectors and Matrices (Arrays) 19
>> A = [2 3 1;1 -5 3; 4 -2 3; 0 1 6]
A =
2 3 1
1 -5 3
4 -2 3
0 1 6
>> A(3,2) % 3rd row, 2nd column of A
ans =
-2
>> A(2:4,2:3) %2-4 rows, 2-3 columns of A
ans =
-5 3
-2 3
1 6
>> A(:,1) %every row, 1st column of A
ans =
2
1
4
0
>> A(2:3,:) %2-3 row, every column of A
ans =
1 -5 3
4 -2 3
1 4 9 7 3
2 5 1 8 4
Deleting elements
One can delete elements by assigning nothing to these elements.
>> v=[2:2:10]
v =
2 4 6 8 10
>> v(2)=[]
v =
2 6 8 10
>> v(2:3)=[]
v =
2 10
>> B
B =
1 4 2 3
3 6 9 2
1 4 9 7
>> B(2:3,:) = [ ]
B =
1 4 2 3
>> C
C =
1 4 2 3
3 6 9 2
1 4 9 7
2 5 1 8
>> C(:,1:2) = [ ]
C =
2 3
9 2
9 7
1 8
Notice the colon: recall that this indicates “all columns” or “all rows.”
Transpose
There are actually several commands for transposing an array, with subtle but important
differences.
1 4 7
A =
1.0000 0.6667
-3.0000 3.1416
>> x', A'
ans =
1
4
7
ans =
1.0000 -3.0000
0.6667 3.1416
>> x.', A.'
ans =
1
4
7
ans =
1.0000 -3.0000
0.6667 3.1416
>> transpose(x), transpose(A)
ans =
1
4
7
ans =
1.0000 -3.0000
0.6667 3.1416
-1 - 2i 4 + 5i
2 - 3i 6 + 7i
Notice that if every number is real, there are no differences between the commands.
But if there are complex numbers, there is a conjugate transpose, and a transpose (see if
you can figure out which ones are which). Other good commands are flip, fliplr,
flipud, etc.
Strings
Strings are arrays of characters rather than numbers, but addressing them can be done
in a similar way.
• An array of characters
• Created by typing characters within single quotes
• Can include letters, digits, symbols and spaces
ans =
3 4 5
>> -3*x
ans =
-3 -6 -9
>> x*y
Error using *
Inner matrix dimensions must agree.
>> A=[1 2;3 4], B = [0 1;-1 1], A*B
A =
1 2
3 4
B =
0 1
-1 1
ans =
-2 3
-4 7
>> x^2
Error using ^
Inputs must be a scalar and a square matrix.
To compute elementwise POWER, use POWER (.^) instead.
>> A^2
ans =
7 10
15 22
In order to do calculations component-wise on an array, use the “.” before the oper-
ator. Thus “.∗” is component-wise multiplication, “.^2” will square every component,
etc.
>>
x.*y
ans =
4 10 18
>> x.^2
ans =
1 4 9
>> A = [1 2 3;4 5 6;-7 -8 -9]
A =
1 2 3
4 5 6
-7 -8 -9
>> A^2
ans =
24 Programming Mathematics Using MATLAB®
Note that, for scalar multiplication, the “.∗” is not necessary, but 3.∗z or z.∗3 will still
work. For addition and subtraction, it will only work if the scalar is first.
>> 3.*z
ans =
30 33
>> z.*3
ans =
30 33
>> 3.+z
ans =
13 14
>> z.+3
z.+3
|
Error: Unexpected MATLAB operator.
>> x.+y
x.+y
|
Error: Unexpected MATLAB operator.
>> abs(A)
ans =
1 2 3
4 5 6
7 8 9
>> exp(A)
ans =
2.7183 7.3891 20.0855
54.5982 148.4132 403.4288
0.0009 0.0003 0.0001
>> sind([0 30 45 60 90])
ans =
0 0.5000 0.7071 0.8660 1.0000
Vectors and Matrices (Arrays) 25
>> x=rand
x =
0.6348
>> y=randn
y =
0.4598
>> z=randi(10)
z =
6
>> p=randperm(5)
p =
5 3 2 4 1
All of the above commands can be modified to generate random vectors and matri-
ces, and other modifications can be made to randi and randperm. See Table 2.1 for
a summary of the basic modifications. See the MATLAB documentation about fancier
modifications, including information on the random number generator.
0.1492
y =
0.7923
z =
6
>> p=randperm(5)
p =
5 3 1 2 4
>> x2=rand(2), y2=randn(2,3)
x2 =
0.1903 0.2686
0.0302 0.9827
y2 =
-1.7616 -0.4471 0.1665
-0.9166 0.1737 -1.0049
>> z2=randi(10,2), z3=randi(10,2,3), z4=randi([-10,10],1,4)
z2 =
7 3
8 9
z3 =
9 1 2
9 5 7
z4 =
-9 1 6 -7
>> p2=randperm(10,3)
p2 =
10 2 7
>> p3=randperm(10,3), z6=randi(10,1,3)
p3 =
1 5 2
z6 =
5 3 3
Note that we can modify rand to generate a random number between any two
numbers and we can modify randn to have a different mean and standard deviation
than the standard normal distribution. See examples below.
>> x=rand(1000,1)*(3) + 5;
>> histogram(x)
In Fig. 2.1 the command histogram is used to quickly display the generated random
numbers.
Vectors and Matrices (Arrays) 27
Example 2.5.2. Create 10,000 random numbers normally distributed with mean
of 100 and standard deviation of 25. Note that our sampling of 10,000 data points
from N (100, 25) would not give a mean and standard deviation of exactly 100 and 25,
respectively.
In Fig. 2.2 the command histogram is used to display these normally distributed ran-
dom numbers.
2.6. Exercises
NOTE: additional exercises that use vectors and/or matrices appear in Appendix C.
1. Do not use MATLAB help or documentation to answer these questions; only
experiment with the commands.
(a) Using the rand command, create a random matrix A1 with 4 rows and 6
columns.
(b) Create a matrix B1 that is the transpose of A1 (there are multiple ways to do
this with one command; choose one).
(c) Using the randi command, create a random ROW VECTOR named u1
with eight elements of integers from 1 to 100.
(d) Create a random COLUMN VECTOR named v1 with nine elements of
integers from −10 to 10.
(e) By using the MATLAB functions length, size, and numel on these ma-
trices and vectors, figure out the differences between these functions, and
come to your own conclusions as to when these functions would be useful.
Write your conclusions nicely on a separate sheet of paper. Write complete
sentences so each part that you are answering is clear. You will be graded
on following directions and not on the accuracy of the descriptions of the
functions, but whether you experimented sufficiently and your conclusions
reflect your experimentation.
Vectors and Matrices (Arrays) 29
(a) E = CD, F = DC, and G = each element of C multiplied with its corre-
sponding element of D.
(b) H = C + D, J = C 2 , and K = each element of C squared.
9. Try to do these as efficiently as possible.
(a) Using rand, generate a random real number between −2π and 2π and store
it in the variable prob9a (do not suppress output).
(b) Using randi, simulate a roll of six dice for the game of Farkle by creating a
vector of six random integers between 1 and 6 (so repeats are allowed) and
store it in the variable farkle (do not suppress output).
(c) Generate a random order for 20 presentations (thus repeats are not allowed,
unlike above) by using the randperm function if the presenters are numbered
1 through 20 (do not suppress output).
(d) Generate a matrix called PowerballTix that will simulate ten Powerball
tickets/drawings (each row will be one drawing). The first five entries of
each row are the “white balls” and the last entry of each row is the “power-
ball” for the drawing. For each row/drawing, the first five columns should
Vectors and Matrices (Arrays) 31
11. Use the matrix M6 in #6 above to answer the following problems. Show the
commands and/or experimentation that helped you reach your conclusions.
(a) What is the difference between sum(M6), sum(M6,2), sum(M6,1), sum(
M6'), and sum(M6, 'all')? Can you come up with an equivalent but
different command for sum(M6,2)?
(b) What is the difference between the commands sort(M6), sort(M6,1), and
sort(M6,2)?
(c) Can you use the same idea for min and max? In other words, do you get
similar results for the commands min(M6), min(M6,2), min(M6,'all'),
etc. as you do with the sum or sort command? If not, what is going on with
these commands and how can you get the same results as in sum(M6,2)?
12. (a) Generate a vector named theta1 of values from 0 to 2π with increments of
π/6 using linspace. (Hint: how many values should you have?)
(b) Generate a vector named theta2 of values from 0 to 2π with increments of
π/6 WITHOUT using linspace.
(c) Calculate the sine of these angles using either theta1 or theta2.
(d) Generate a table of Cartesian coordinates corresponding to these angles on
the unit circle by building a matrix called Cart. The first column should be
32 Programming Mathematics Using MATLAB®
Plotting in MATLAB®
3.1. Basic 2D plots
There are many ways to plot data, curves, and/or functions. We will not cover all
plotting commands, but hopefully after this chapter you will be able to use other plotting
commands (such as pie, etc.) and be able to customize your plots easier.
We will start with plotting functions. If you are familiar with the command ezplot,
this command is outdated and should be replaced by fplot, so we will not discuss
ezplot. Both ezplot and fplot are useful but do not have as much versatility as the
plot command. With fplot you can control the domain, colors, markers, etc. as we
will discuss in this chapter but MATLAB® decides which data points to use within your
domain to create the plot. For example, notice what the commands fplot(@(x)x.^3),
fplot(@(x)sin(x)), and fplot(@(x)sin(x), [-2,2]) create.
With the command plot we can control which points, and thus how many points
are used to create the plot(s). We can also plot data points. Most of the examples in this
chapter will use plot. Much of the syntax for modifying colors, creating multiple plots,
etc. are the same with fplot and plot.
In order to plot a mathematical function using plot, follow these steps.
Step 1: define the domain as a vector. This is where the linspace command can come
in handy, and when you will want to SUPPRESS THE OUTPUT.
x = linspace(-5,5);
Step 2: calculate the y-values for each of the x-values in your domain USING
COMPONENT-WISE CALCULATIONS. Note that fplot needs component-wise
calculations as well.
y = x.^3;
Step 3: Plot the inputs and outputs using the plot command. What the plot(x,y)
command does is plot each point (xk , yk ) in the vectors x and y (or whatever you have
called these variables). By default, it connects these points in the order of the vectors
with a blue line. If there are enough points in the vectors, you get a smooth curve as
expected in this case.
We will have to add labels and titles if we want them (shown later). One can also
just as easily define the vectors within the plot command. For example, the following
code would produce the same figure as in Fig. 3.1:
x=linspace(-5,5);
plot(x,x.^3)
Notice also the use of the axis command so that the plot can be seen better. We
must make sure the vertices are in the proper order so that when they are connected,
we get the desired effect.
Plotting in MATLAB® 35
Figure 3.2 Domain examples. (A) Bad domain: x = -5:5, (B) Better domain: x = -5:0.01:5.
Figure 3.3 Reordering points. (A) x=[0 0 1 1]; y=[0 1 0 1], (B) x=[0 0 1 1];
y=[0 1 1 0].
We can make this even better by remembering to include the first point as the
last point so all vertices are connected. Also, for Fig. 3.4(B), we added the command
axis equal after the axis([-0.2 1.2 -0.2 1.2]) command so that what is shown
does indeed look like a square as desired.
Figure 3.4 Better squares. (A) x=[0 0 1 1 0]; y=[0 1 0 1 0], (B) Using axis equal.
As seen in Figs. 3.3 and 3.4, you can control the length of the axes shown and/or
aspect ratios. You can even set axis off. You can change the limits of the x-values
or y-values shown in the figure by using xlim and/or ylim commands. Fig. 3.12 uses
the xlim command. You can also use the axis command. The axis command is in
the form [xmin xmax ymin ymax], with the addition of zmin zmax elements for a
three-dimensional figure (discussed in Chapter 4). Thus axis([-2 2 -5 5]) will set
the axes to be [−2, 2] × [−5, 5]. This command is equivalent to xlim([-2,2]), ylim
([-5,5]).
To change the aspect ratio, especially when plotting circles, squares, etc. you may
want to use axis equal or axis square. Another useful one is axis tight. To reset
to the default, use axis normal. In Fig. 3.5 are different examples showing the differ-
ences between some of the axis settings to graph y = sin(x) for x ∈ [−2π, 2π ]. A word
of advice: if you are expecting lines and/or planes to look orthogonal (perpendicular)
and they do not, it could be the aspect ratio of the figure. Learn from me, first try
axis equal before spending too much time double checking and triple checking your
math! This is demonstrated in Section 4.4.1.
To see the importance of setting the aspect ratio using axis, consider the following
MATLAB code that generates Fig. 3.6(A):
t=linspace(0,2*pi);
x=cos(t); y=sin(t);
plot(x,y)
If you look closely, this is a parameterization of the unit circle, and yet the figure
looks more like an ellipse. If we use the command axis([-1.5 1.5 -1.5 1.5]) to
Plotting in MATLAB® 37
Figure 3.5 Different axis settings with sine. (A) Default axis, (B) axis tight, (C) axis equal
and (D) axis square.
establish that [xmin xmax ymin ymax] should have values [-1.5 1.5 -1.5 1.5], it
still looks like an ellipse (Fig. 3.6(B)).
Setting the axis limits in Fig. 3.6(B) still does not achieve the desired picture. Other
axis properties then need to be set, such as axis square and axis equal (Fig. 3.7).
A word of caution: when you are combining both setting the limits and the aspect
ratios, the order of these commands is important! You may need to experiment
with different orders to see the difference and which order gives you the desired effect.
For example, in the y = sin(x) plot below, if you have the axis equal before or after
38 Programming Mathematics Using MATLAB®
Figure 3.6 Unit circle. (A) Default axis and (B) axis([-1.5 1.5 -1.5 1.5]).
Figure 3.7 Axis Examples. (A) The default axis, (B) axis square and (C) axis equal.
the ylim([-2,2]) commands, you get different results (see Fig. 3.8). Also, if you add
plots after setting the axes, the axes are already “set” so the additional plot will not
change the limits or aspect ratio.
x=linspace(-10,10);
y=sin(x);
plot(x,y)
axis equal
axis([-5, 5, -2,2])
Plotting in MATLAB® 39
Figure 3.8 Effects of order of commands. (A) axis equal first, (B) axis equal second, (C) Only
axis equal and (D) Only axis([-5, 5, -2,2]).
Experiment with plotting the circle, setting the axes from −1.5 to 1.5 and axis
equal. Have both commands, in different orders, and just one of those commands to
see the differences in the plots created. Experimenting you may notice the following:
x = linspace(-2*pi,2*pi);
y = sin(x);
y2 = 3*sin(x);
y3 = sin(3*x);
plot(x,y,x,y2,x,y3)
xlabel('x'),ylabel('y')
title('Example 1 of Multiple Plots')
Notice that we also put in axes labels and a title in the above plot.
You can easily create a legend, making sure the text within the legends is in the same
order as the order within the plot command. By comparing Figs. 3.9 and 3.10, notice
the effect of the axis tight command. In Fig. 3.10(B), we have changed the location
of the legend by using the command
Plotting in MATLAB® 41
Figure 3.10 Using legend and axis tight. (A) Default legend location, (B) Changing location
of legend.
x = linspace(-2*pi,2*pi);
y = sin(x);
y2 = 3*sin(x);
y3 = sin(3*x);
plot(x,y,x,y2,x,y3)
xlabel('x'),ylabel('y')
title('Example of Multiple Plots')
legend('y=sin(x)', 'y=3sin(x)', 'y=sin(3x)')
axis tight
Another way to have multiple plots is to use the hold on and hold off commands.
The hold on command tells MATLAB to hold the active figure window open to add to
it with any subsequent plotting commands until the hold off command appears. Thus
you can mix various plot commands in one figure window (when appropriate). For
example, you can use the plot command and the scatter command on one figure, as
in Fig. 3.11(A).
Figure 3.11 Using hold on and hold off command. (A) Using scatter, (B) Using plot.
Note that you can just as easily use the command plot instead of scatter, although
for the plot command you must specify to just plot the points with a marker that you
designate, rather than connect the points (see Fig. 3.11(B)).
When using hold on and hold off for multiple plots, the lines/markers will cycle
through the default colors (new from MATLAB version R2014b on). The grid on
command can also be useful.
x = linspace(-2*pi,2*pi);
y= sin(x);
y2=3*sin(x);
y3 = sin(3*x);
plot(x,y)
hold on
plot(x,y2)
plot(x,y3)
xlabel('x'),ylabel('y')
title('Example of Multiple Plots')
xlim([-4,4])
grid on
legend('y = sin x', 'y = 3sin x', 'y = sin(3x)', 'Location', 'NorthWestOutside')
hold off %% DON'T FORGET TO HOLD OFF!!
Plotting in MATLAB® 43
Note that the default first color is a different blue ([0, 0.4470, 0.7410])
from 'b'= [0, 0, 1], which is new from MATLAB version R2014b on. The
default line style is solid, the default LineWidth is 0.5 and the default Mark-
erSize is 6. Table 3.1 lists the possible basic colors, line styles, and markers. One, two,
or three of these specifications can be defined in any order.
44 Programming Mathematics Using MATLAB®
Note that you can use the “short name” shown above, the long name, or the RGB
Value of these basic eight colors as shown in Table 3.2. Also the dashes, dash-dots, etc.
may not appear nicely if you have too many points in the vectors plotted.
Consider Fig. 3.11. Because the default colors are cycled through (which is new
starting in MATLAB version R2014b), the line and data points are different colors but
we may want them to be the same color. One way is to specify the colors.
x = randi(10,1,50);
y = randi(10,1,50);
Plotting in MATLAB® 45
scatter(x,y, 'b')
hold on
plot(x,x, 'b')
hold off
Another way is to reset to the first default color as is done in the following code:
scatter(x,y)
hold on
ax = gca;
ax.ColorOrderIndex = 1; % resets back to first color for next plot
plot(x,x)
hold off
The lines command is very useful to capture the colors of the current color map.
Since there are 7 different colors, lines(7) will return a matrix where each row is the
RGB code for the colors. Thus you can store those and assign them. The code below
would return a similar plot as in the code above.
Another way is to specify different colors other than the basic eight colors dis-
cussed above is to specify colors by their RGB triple (for some examples, see http://
www.rapidtables.com/web/color/RGB_Color.html). While many RGB colors are
triples with numbers from 0 to 255 where (000) is black and (255, 255, 255) is white,
MATLAB expects each number in the triple to be a number between 0 and 1. Thus
you can take the RGB triple (255, 69, 0) for the color “orange red” and define it in
MATLAB as OrangeRed = 1/255∗[255,69,0];. Likewise, you can define the color
LoyolaGreen = 1/255∗[0, 104, 87]; then one can use the defined color triple in
your plot commands (see Fig. 3.14).
3.5.2 Subplots
The command subplot(m,n,k) is used to create a matrix of subplots within the same
figure window. The number m is how many rows, n is how many columns, and k is which
Plotting in MATLAB® 47
subplot the following commands apply to. NOTE: you do not need to use commas to
separate the m, n, and k. It is easiest to explain by viewing an example (see Fig. 3.15).
subplot(2,2,1)
x = linspace(-10,10);
y = cos(x);
plot(x,y)
title('y = cos(x)')
ylim([-2,2])
subplot(2,2,2)
y = 1/2*cos(x);
plot(x,y)
title('y = 1/2cos(x)')
ylim([-2,2])
subplot(2,2,3)
y = 2*cos(x);
plot(x,y)
title('y = 2cos(x)')
axis([-5 5 -2, 2])
subplot(2,2,4)
y = cos(x + pi/4);
plot(x,y)
title('y = cos(x + pi/4)')
ylim([-2, 2])
48 Programming Mathematics Using MATLAB®
Notice that the numbering goes across the rows, first, then down. There is no way
to make a “global title” without using the text command, and there it is not as nice
because of having to specify the exact placement of the text.
One can have a subplot stretch across elements (see Fig. 3.16):
clf
subplot(141)
x=linspace(-5,5);
y=sin(x);
plot(x,y)
subplot(142)
y = sin(2*x);
plot(x,y)
subplot(1,4,3:4)
y=sin(1/2*x);
plot(x,y)
Issue with subplots: once you have used subplot commands, any plotting com-
mands will apply to the subplot currently set. Thus if I now have enter additional
plotting commands, it will place it in the last subplot, in this case it will place it in the
3-4 spot from the above. Here is an example. If this code immediately follows the above
code, the result is Fig. 3.17. Thus one should use the command clf or close all
between subplots and subsequent plots to “reset” things.
plot(x,-abs(x))
Plotting in MATLAB® 49
y = linspace(-5,5);
x=y.^2+2*y-3;
plot(x,y)
xlabel('x'),ylabel('y')
x = 3 cos t,
y = 2 sin t,
for t ∈ [0, 2π ].
t = linspace(0,2*pi);
x = 3*cos(t);
50 Programming Mathematics Using MATLAB®
y = 2*sin(t);
plot(x,y)
xlabel('x'),ylabel('y')
title('Example of Parametric Equations')
axis equal
axis([-5 5 -5 5])
grid on
t = linspace(0,2*pi);
r = 1 + sin(10*t);
x = r.*cos(t);
y = r.*sin(t);
plot(x,y)
xlabel('x'),ylabel('y')
Instead of using the conversion equations, one can have MATLAB do the conversion
using the command pol2cart. You can have a polar axis with the command polarplot
Figure 3.19 Polar curves. (A) Default linspace, (B) 300 elements.
Figure 3.20 Polar curves. (A) With pol2cart (A) and (B) with polarplot.
(see Fig. 3.20). This command wants values for θ and r in polar coordinates. Note that
the command polar is no longer advised to use.
%% using pol2cart
t = linspace(0,2*pi,300);
r = 1 + sin(10*t);
[x,y]=pol2cart(t,r);
plot(x,y)
52 Programming Mathematics Using MATLAB®
xlabel('x'),ylabel('y')
axis equal
%% using polarplot
t = linspace(0,2*pi,300);
r = 1 + sin(10*t);
polarplot(t,r)
3.7. Exercises
1. The main span of the Golden Gate Bridge [9] can be roughly modeled with a
catenary equation
x
y = 4200 cosh − 3954
4346
for |x| ≤ 2100. You can also model it with a quadratic over the same domain:
y = 0.00011338x2 + 246.
(a) Plot both of them on the same figure, making the catenary in red and the
quadratic in black (default width). CAREFUL! How many elements should
be in your domain?
(b) Plot the catenary curve, making the line thicker than default and setting
'color' [8,21] to be the RGB vector for an approximation to Golden
Gate’s International Orange:
1
(155, 25, 0).
255
Also use the command “axis equal”.
2. The Gateway Arch in St. Louis was designed by Eero Saarinen and the central
curve is modeled by a catenary
1
(155, 25, 0).
255
(c) What is the height of the arch at its center? State the exact value and use
MATLAB to estimate the answer if needed (work on paper).
Plotting in MATLAB® 53
(d) At which point(s) is the height 100 m? State the exact value and use MAT-
LAB to estimate the answer if needed (work on paper).
(e) What is the slope of the arch at the points in part (d)? Use MATLAB to
estimate the answer if needed and show any work on paper.
(f) Create a second plot where the curve of the arch is shown, and the tangent
lines at these points is shown in red. Mark the points with a black “x”.
2x2 − 5x + 11
3. Consider the function f (x) = 2 . We will work to make a decent graph
x − 7x − 8
(closer to one you may see in a textbook) in steps.
(a) Notice that the function has (a) vertical asymptote(s). What are they? State
your answer as a full sentence, showing all work on paper. (Your answers
should be equations for vertical lines!)
(b) This function also has horizontal asymptote(s). What are they? State your
answer as a full sentence, showing all work on paper.
(c) Plot the function y = f (x) using fplot without any other settings specified
other than axes labels and a title.
(d) Plot the function y = f (x) for −20 ≤ x ≤ 20 using plot without any other
settings other than axes labels and a title. Notice this may not look like the
way you may see the graph for this function in a textbook.
(e) Now use plot with y = f (x) for −20 ≤ x ≤ 20 with some modifications.
Set the range of the y-axis from −20 to 20. Notice again this may not look
“textbook quality”.
(f) Now use plot with y = f (x) (same domain and range for the y as above)
by dividing the domain into separate domains for each side of the vertical
asymptotes. The graphs of each piece should all be the same color so that it
looks like the same function.
(g) Do the same as in part (3f) but also graph the vertical asymptote(s) as red,
dashed lines. Graph the horizontal asymptotes as black, dotted lines.
4. Consider the function f (x) = 13 x4 − 8x2 + 4x + 1.
(a) Using calculus, find the first and second derivatives of f (x).
(b) Plot y = f (x), y = f (x), y = f (x) on the same graph/figure for x ∈ [−5, 5].
Make sure you use a descriptive legend for each of the functions plotted.
(c) EXTRA CREDIT TWO POINTS: use axis off and create horizontal
and vertical lines (in black) for the x and y axes. The axes should be of
appropriate length for the graph. (There is a way to do this without knowing
the height and width ahead of time!)
5. Consider the functions f (x) = cos(3x) − 1 and g(x) = 2x sin(x).
f (x)
(a) Using calculus, find the exact value of lim on paper, showing all work.
x→0 g(x)
(b) To demonstrate the calculus, plot y = f (x)/g(x), y = f (x)/g (x), and y =
f (x)/g (x) near x = 0 on the same graph. You may have to adjust your axes
54 Programming Mathematics Using MATLAB®
to make it a nice looking graph and make sure you use a descriptive legend
so one can tell which functions are which.
6. Consider the functions f (x) = sec(5x) − 1 and g(x) = 7x sin(x).
f (x)
(a) Using calculus, find the exact value of lim on paper, showing all work.
x→0 g(x)
(b) To demonstrate the calculus, plot y = f (x)/g(x), y = f (x)/g (x), and y =
f (x)/g (x) near x = 0 on the same graph. You may have to adjust your axes
to make it a nice looking graph and make sure you use a descriptive legend
so one can tell which functions are which.
7. Create a script that displays the following. The amount A(t) of an initial investment
P in an account paying an annual interest rate r at time t is given by
r nt
A(t) = P 1 +
n
where n is the number of times the interest is compounded in a year and t is the
number of years. If the interest is compounded continuously, the amount is given
by
A(t) = Pert .
Consider an investment of $7500 put into a trust-fund account at an annual interest
rate of 2.5% for 21 years. Show the difference in the value of the account when
the interest is compounded annually, quarterly, and continuously by plotting A(t)
from t = 15 to t = 21 for these three situations on the same figure. Use a different
line type (color and/or type of line), label the axes, create a meaningful legend and
title for the plot.
8. For a calculus problem, you want to plot the region enclosed by the curves
x = y2 − 3, x = ey + 1, y = −1, y = 1.
Create a script file to plot these four curves, making the first two blue and red,
respectively, and the last two curves in black. Set the window to be [−5, 5] ×
[−5, 5].
9. If a projectile is thrown or fired with an initial velocity of v0 meters per second at
an angle α above the horizontal and air resistance is assumed to be negligible, then
its position after t seconds is given by the parametric equations
1
x = (v0 cos α)t, y = (v0 sin α)t − gt2 ,
2
where g is the acceleration due to gravity (9.8 m/s2 ).
(a) According to Guinness World Records, the fastest lacrosse shot was recorded
at 53.6 m/s in 2015 [12]. Use this speed as initial velocity v0 , and α = 8.5◦
to answer the following:
Plotting in MATLAB® 55
11. Plot the following polar plots on one figure using subplot. Be sure that the titles
name the curves, or give the equation if it is unnamed. Also be sure to choose
the correct domain for each to make sure for each to make sure you produce the
entire curve. Plot these using the pol2cart command.
(a) Freeth’s nephroid r = 1 + 2 sin(θ/2);
(b) Hippopede r = 1 − 0.8 sin2 θ ;
(c) Butterfly curve [6] r = esin θ − 2 cos(4θ ) + sin5 (θ/12), θ ∈ [0, 50π ];
(d) r = sin2 (4θ ) + cos(4θ );
(e) r = 2 + 6 cos(4θ );
(f) r = 2 + 3 cos(5θ ).
12. Using Kepler’s first law of planetary motion, one can obtain a basic model of the
orbits of planets and dwarf planets around the sun can be modeled using the polar
equation [24, p. 727]
a(1 − e2 )
r=
1 + e cos(θ )
where a is the semi-major axis and e is the eccentricity of the planet. The values
of several semi-major axes (a) and eccentricities (e) for our solar system [23] are in
Table 3.3.
(a) Plot the orbits of Mercury, Venus, Earth and Mars in one figure using
polarplot on the polar plane, making sure to have a legend, title, etc.
You may have to order the commands appropriately so all orbits appear on
the figure. Plot Mercury in blue, Venus in yellow, Earth in green, and Mars
in red.
(b) Plot the orbits of Earth, Neptune, and Pluto in one figure using polarplot
on the polar plane, making sure to have a legend, title, etc. As above, you
may have to order the commands appropriately so all orbits appear on the
figure. Plot Earth in green, Neptune in cyan and Pluto in magenta.
13. This problem will show the value of working with log-scales in plots. The efficacy
of two drugs are given in Table 3.4 by measuring the percentage of binding of the
Plotting in MATLAB® 57
drug to the necessary receptor at different concentration levels in moles per liter,
or molars (M).
(a) Plot the data points with concentration level of the drug on the horizontal
axis and binding percentage on the vertical scale. First use a linear scale
(using plot), being sure to label the axes and create a legend. Use different
markers for drug A and drug B and connect the markers with a different
line (solid, dotted, etc.).
(b) Create a similar plot of the data but instead use a semi-log scale (using
semilogx).
CHAPTER 4
Three-Dimensional Plots
4.1. Vector functions or space curves
Vector functions (3D parametric equations) are defined and plotted similarly to 2D
plots, except one must use the command fplot3 instead of fplot and plot3 instead
of plot.
One can fine-tune the domain used for t and color(s) used, but for more flexibility
and control use plot3.
Step 1: Define your inputs (the t). This is where linspace comes in handy; make sure
you SUPPRESS THE OUTPUT.
t = linspace(0,10*pi,200);
x = t.*cos(t);
y = 4*t+1;
z = t.*sin(t);
Step 3: Plot the defined vectors using the plot3 command to get Fig. 4.1(A).
plot3(x,y,z)
xlabel('x'),ylabel('y'),zlabel('z')
As discussed in the previous chapter, you must be careful on how you define your
domain to make sure you get the expected plot, as seen in Fig. 4.1(B).
You can add plots, titles, label axes, etc. to your figure just as in 2D plots.
% multiple plots
t = linspace(0,3*pi);
x = t.*cos(t);
y = 4*t+1;
z = t.*sin(t);
s=linspace(-5,5);
x2 = 2*pi + s;
y2 = 2*pi*s;
z2 = 8*pi + 4*s;
plot3(x,y,z,x2,y2,z2)
xlabel('x'),ylabel('y'),zlabel('z')
You can add plots using hold on and hold off, and here we are also adding a point
to the graph (see Fig. 4.2).
As in 2D, you can change the window using xlim, ylim and/or zlim commands (try
in the command window) or the axis command (see Fig. 4.3). Notice these commands
Figure 4.1 Vector functions. (A) Vector function example, (B) Bad domain example.
Three-Dimensional Plots 61
may not get the desired result and it may be better to adjust your domains instead. The
grid on command is also used in Fig. 4.3.
t = linspace(0,10*pi);
x = t.*cos(t);
y = t.*sin(t);
z = 4*t;
s=linspace(-5,5);
x2 = 2*pi + s;
y2 = 2*pi*s;
z2 = 8*pi + 4*s;
plot3(x,y,z)
hold on
plot3(x2,y2,z2,'k')
xlabel('x'),ylabel('y'),zlabel('z')
62 Programming Mathematics Using MATLAB®
plot3(2*pi,0,8*pi,'*k')
zlim([0,60])
title('Example of Multiple Plots and Other Commands')
legend('vector curve', 'tangent line')
grid on
hold off %% DON'T FORGET TO HOLD OFF!!
fmesh(@(x,y) 0.5*cos(0.5*x).*sin(y))
%%
fsurf(@(x,y) exp(y).*cos(pi*x), [-4,4,0,2])
The commands that plot the three-dimensional surfaces establish points (x, y, z)
of the surface to be corresponding elements in the matrices X, Y , and Z and then
“connect-the-dots” as in the two-dimensional plots. One can create these matrices sep-
arately, but if they are not formed from datasets then many times the surface(s) are the
result of functions. Thus the steps to establish the domain and then using component-
wise calculations are especially important.
4y
Example 4.2.1. Graph the surface f (x, y) = for −10 ≤ x ≤ 10 and −5 ≤
x2 + y2 + 1
y ≤ 5.
Step 1: Establish the domain by creating vectors. They do not need to be the same size.
Step 2: Create the matrices X and Y based on the domain. The easiest way to do this
is by using the command meshgrid.
Step 3: Calculate the corresponding Z using component-wise calculations on the ma-
trices X and Y .
Step 4: Plot the surface. The most common commands are mesh and surf as seen in
Fig. 4.4.
Note that Step 1 and Step 2 can be combined into one step, but for clarity they are
shown separately.
Three-Dimensional Plots 63
Figure 4.4 Plotting surfaces. (A) Using mesh(x,y,z), (B) Using surf(x,y,z).
>> [x,y]=meshgrid(1:5,6:8)
>> z=x.*y
x =
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
y =
6 6 6 6 6
7 7 7 7 7
8 8 8 8 8
z =
6 12 18 24 30
7 14 21 28 35
8 16 24 32 40
Once the matrices are created, three-dimensional plot commands will use as points the
corresponding elements of these matrices, and then connect those points. Thus the first
point plotted in the above example will be the point (x, y, z) = (1, 6, 6), and the last
point will be (5, 8, 40) (see Fig. 4.5).
64 Programming Mathematics Using MATLAB®
Figure 4.6 Domain examples. (A) Default linspace, (B) Using 40 values.
[x,y]=meshgrid(linspace(-5,5));
z=5-sqrt(x.^2 + y.^2);
surf(x,y,z)
Three-Dimensional Plots 65
Notice in the code above, the meshgrid command has one input vector. This com-
mand is equivalent to the command meshgrid(linspace(-5,5),linspace(-5,5))
but is more efficient.
If one does not use enough values, the surface can appear jagged, as in Fig. 4.7(A).
Too many values as in Fig. 4.7(B) can create a bad figure, also. Note that for some sur-
faces even having 40 instead of 60 in your vector can make it appear jagged. This second
example shown in Fig. 4.7(B) was created by using the command [x,y]=meshgrid
(-9:.05:9); for z=y.∗sin(x). This is common if one is in the habit of using the
colon operator for creating domain vectors in 2D plots. When using this notation to
create 3D plots, this can create vectors and thus matrices of a much larger size than
needed, and can greatly slow down MATLAB in performing both the calculations com-
mand(s) and plotting command(s). Think about the size of the matrices created if the
domain was from −100 to 100 and one created a vector -100:.01:100!
[x,y]=meshgrid(linspace(-4,4));
z = -150*x.*y.*exp(-x.^2-y.^2);
contour(x,y,z)
66 Programming Mathematics Using MATLAB®
Figure 4.8 Level Curves. (A) contour(x,y,z), (B) contourf(x,y,z) and (C) contour(x,y,
z,20).
The above code creates Fig. 4.8(A). You can create a filled contour as in Fig. 4.8(B)
using contourf.
One can adjust the number of level curves shown by having a fourth argument as
in Fig. 4.8(C); otherwise MATLAB automatically chooses the number of level curves
drawn.
To create labels, or to adjust which values the level curves are shown; see the code
below. The output of the code below is in Fig. 4.9.
[c,h]=contour(x,y,z);
clabel(c,h)
%% Forcing values of levels (with labels)
cvalues=-20:4:20;
[c,h]=contour(x,y,z,cvalues);
clabel(c,h)
You can show level curves in 3D, and even add a mesh surface or filled surface as in
Fig. 4.10.
[x,y]=meshgrid(linspace(-2,2,55));
z1=y.*exp(x.^2-5);
Three-Dimensional Plots 67
Figure 4.9 Modifying level curves. (A) Level Curve with Labels, (B) Specifying Levels.
Figure 4.10 Level curves in 3D. (A) contour3(x,y,z,20), (B) meshc(x,y,z) and (C) surfc
(x,y,z).
Figure 4.11 Multiple plots and modifying colors. (A) No modifications, (B) Specifying Colors.
68 Programming Mathematics Using MATLAB®
mesh(x,y,z1)
xlabel('x'),ylabel('y'),zlabel('z')
hold on
z2=1/2*x.*cos(y);
mesh(x,y,z2)
hold off
%% Modifying colors
LoyGreen = 1/255*[0, 104, 87];
mesh(x,y,z1,'EdgeColor',LoyGreen)
xlabel('x'),ylabel('y'),zlabel('z')
hold on
surf(x,y,z2,'FaceColor','y', 'EdgeColor','r')
hold off
Figure 4.12 Colormaps. (A) colormap jet, (B) colormap default and (C) colormap bone.
Three-Dimensional Plots 69
The default view is view(-37.5, 30), as seen in Fig. 4.15(A). By changing the
viewpoint to be similar to what is shown in Fig. 4.14 (using view(30,30)), we get
Fig. 4.15(B).
Using the view command, you can look down at the xy-plane, xz-plane, and
yz-plane (see Fig. 4.16). This will be explored in the exercises.
As mentioned in the MATLAB documentation, there are some limitations of control
with this command. To gain more control of the view, you can use the camera properties
but these are not discussed here.
70 Programming Mathematics Using MATLAB®
Figure 4.15 View examples. (A) The default view, (B) Using view(30,30).
Figure 4.16 View examples. (A) xy-plane view, (B) xz-plane view.
Example 4.4.1. Graph the surface f (x, y) = 2x2 + y2 along with its tangent plane and
normal vector at the point (1, 1, 3).
From multivariable calculus, we get that the equation for the tangent plane is z =
4x + 2y − 3 and the parametric equations for the normal vector are
x = 1 + 4t,
y = 1 + 2t,
Three-Dimensional Plots 71
z = 3 − t.
Graphing it and then adjusting the view gives us the figures in Fig. 4.17.
% surface
[x,y]=meshgrid(linspace(-4,4,50));
z=2*x.^2+y.^2;
% plane
z2 = 4*x+2*y-3;
% vector
t=linspace(-1,1.5);
x3=1+4*t;
y3=1+2*t;
z3=3-t;
% graphing
mesh(x,y,z,'EdgeColor','black')
hold on
surf(x,y,z2,'FaceColor','blue')
plot3(x3,y3,z3,'r', 'LineWidth',2)
hold off
xlabel('x'),ylabel('y'),zlabel('z')
When first seeing these figures, you may check and recheck their calculus and won-
der what is going on as the normal vector does not appear to be perpendicular to the
tangent plane. The problem is not the calculus; it is the aspect ratios of these figures.
These can be fixed by using axis equal with some adjustments. If using zlim still does
Figure 4.17 Different view settings for Example 4.4.1. (A) default view: view(-37.5,30), (B)
view(65,25).
72 Programming Mathematics Using MATLAB®
not achieve the desired picture, as mentioned previously you may also want to adjust
the original domains to get the desired picture (see Fig. 4.18).
[x,y,z]=sphere(30);
mesh(x,y,z) % unit sphere
hold on
surf(x+3,y+2,z-1) % sphere with center (3,2,-1)
r=0.5;
mesh(r*x-1,r*y+2,r*z+1,'FaceColor',[0.5,0.5,0.5],...
'EdgeColor', 'k') % sphere resized, moved and recolored
axis equal
xlabel('x'),ylabel('y'),zlabel('z')
Three-Dimensional Plots 73
Figure 4.19 Spheres using axis equal. (A) default sphere, (B) sphere(50) and (C) sphere
(10).
The command cylinder works similarly to the sphere command and will generate
a unit circular cylinder: a cylinder of radius 1 and height 1 with the center of circle at
(0, 0) in the xy-plane (see Fig. 4.21(A)). The command cylinder(f) will create a
cylinder using f as the profile curve; in other words, f is the radius of the cylinder at
equally spaced heights along the cylinder (see Fig. 4.21(B)). Thus f could be one value
of a vector of values. The command cylinder is equivalent to cylinder(1). The
command cylinder(f,n) will create a cylinder using f as the profile curve but using
n equally spaced points around its circumference (see Fig. 4.21(C)). Thus cylinder is
equivalent to cylinder(1,20).
As in the case with the sphere command, using [x,y,z]=cylinder(f,n) al-
lows for more control over modifying the cylinders generated using transformations
on (x, y, z) (see Fig. 4.22).
74 Programming Mathematics Using MATLAB®
Figure 4.21 Cylinders using axis equal. (A) default cylinder, (B) cylinder(0.5) and (C)
cylinder(2,50).
[x,y,z]=cylinder(1,50);
mesh(x,y,z)
hold on
surf(x-1,y+2,2*z)
surf(2*x-1,2*y+1,0.5*z+3,'FaceColor',[0.3,0.3,0.3])
hold off
axis equal
xlabel('x'),ylabel('y'),zlabel('z')
t=linspace(0,2*pi);
f=2*sin(t) + t + 2;
[x,y,z]=cylinder(f,50);
mesh(x,y,z)
xlabel('x'),ylabel('y'),zlabel('z')
%%
v1=[0,10];
v2=0:10;
v3=0:0.5:10;
v4=v3.^2;
[x,y,z]=cylinder(v2,50);
mesh(x,y,z)
xlabel('x'),ylabel('y'),zlabel('z')
Experiment with the above code to see the difference between using v1, v2 (shown),
v3, and v4.
If you would like to have the cylinder horizontal instead, it may be easiest to define
the matrices as usual but switch the variables in the plotting command (see Fig. 4.24).
You can then adjust the cylinder’s length, width, and center via transformations similar
to what is done in Fig. 4.22. These adjustments will be explored in the exercises.
Three-Dimensional Plots 75
Figure 4.23 Cylinders with non-constant profile f. (A) cylinder(f,50), (B) cylinder
(0:10,50).
t=linspace(0,2*pi);
f=2*sin(t)+t + 2;
[x,y,z]=cylinder(f,50);
mesh(3*z+2,x,y) % horizontal, shifted cylinder
xlabel('x'),ylabel('y'),zlabel('z')
Figure 4.25 Cylindrical coordinates example. (A) Using conversion equations, (B) Using pol2cart.
Example 4.5.1. Graph the surface z = r that is given in cylindrical coordinates for
r ∈ [−2, 2] and θ ∈ [0, 2π].
xlabel('x'),ylabel('y'),zlabel('z')
axis equal
%% Using pol2cart
tdomain2=linspace(0,2*pi); rdomain2 = linspace(-2,2);
[t2,r2]=meshgrid(tdomain2,rdomain2);
z2=r2;
[x2,y2,z2]=pol2cart(t2,r2,z2);
mesh(x2,y2,z2)
xlabel('x'),ylabel('y'),zlabel('z')
axis equal
axis equal
%% using sph2cart
clf
theta=linspace(0,2*pi);
phi=linspace(0,pi/4);
[t,p]=meshgrid(theta, phi);
rho = 3+0*t;
[x,y,z]=sph2cart(t,p,rho);
mesh(x,y,z)
xlabel('x'), ylabel('y'), zlabel('z')
axis equal
Note that there are other commands such as cart2sph and cart2pol but these are
not discussed here.
4.6. Exercises
1. A helix is a three-dimensional curve (shape of a spring) that can be modeled by
the following equations:
x = a cos t,
y = a sin t,
z = bt,
where a is the radius of the helical path and b is a constant that determines the
“tightness” of the path.
(a) Plot a basic helix (a = b = 1) for five complete turns (be careful: what should
be your domain for t equal)?
The DNA molecule has the shape of a double helix, where one helix can be
modeled by the above equations. The radius of each helix of the DNA molecule
is about 10 angstroms (1 Å = 10−8 cm). Each helix rises about 34 Å during each
complete turn [26].
Figure 4.26 Spherical coordinates. (A) Calculus definition of φ , (B) MATLAB definition of φ and (C)
Using sph2cart.
Three-Dimensional Plots 79
(b) Figure out what a and b should equal for the single DNA helix. Work on
paper (if any) should be turned in and the answers should be text on the
webpage. Have the units in angstroms and state the EXACT VALUES.
(c) Plot five complete turns of the DNA helix (what should be the domain for
t equal?).
(d) Plot the helix for 100 complete turns. BE CAREFUL! In order for this to
be shown correctly (i.e., showing all of the turns), you will have to define
your domain correctly.
(e) Estimate the full length of ONE COMPLETE TURN of the DNA helix
using the arc length formula
d 2 2 2
dx dy dz
L= + + dt.
c dt dt dt
Figure out what c and d should be in the integral and calculate L on paper
using calculus, showing all work. Turn in your work on paper and state the
EXACT VALUE of your answer as text on the webpage (in angstroms).
Also use MATLAB to give a numerical approximation of this answer in
angstroms.
(f) In one cell in the human body, it has been said that DNA makes about
2.9 × 108 complete turns. Using your (exact value) answer in part (1e), use
MATLAB to give a numerical approximation of the FULL LENTH of the
DNA helix, in meters.
(g) It has been said that there are about 1013 cells in the human body. Use this,
along with your answer in part (1f) to estimate the length of all of the DNA
in a human body. The average distance between the Earth and Mars is 225
million km [22]. Would the stretched out DNA in a human body reach
Mars? If so, how many roundtrips would there be from the Earth to Mars
and back?
2. Graph the following 3D surfaces. For each of these, have the titles specify the
problem number and part, and if the surface has a special name include that as
well. Label the axes.
(a) z = 1 − |x + y| − |y − x|. Use fsurf.
(b) z = x3 − 3xy2 , x, y ∈ [−15, 15] × [−15, 15] (monkey saddle). Use mesh.
sin(x2 + y2 )
(c) z = , x, y ∈ [−5, 5] × [−5, 5]. Use surf and have the z-axis go
(x2 + y2 )
from −2 to 2.
(d) z = sgn(xy) sgn(1 − 100x2 + 100y2 ), x, y ∈ [−10, 10] × [−10, 10]. Use surf
and 50 points each for the domains of x and y.
(e) z = sgn(xy) sgn(1 − 100x2 + 100y2 ), x, y ∈ [−10, 10] × [−10, 10]. Use mesh
and 200 points each for the domains of x and y.
80 Programming Mathematics Using MATLAB®
(f) z = sin x + sin y, x, y ∈ [0, 6π] × [0, 20]. Use axis equal and your choice of
mesh or surf.
(g) Graph the level curves (contour lines) for z = sin(x − y), x, y ∈ [−10, 10] ×
[−10, 10].
(h) Graph the level curves (contour lines) for z = 1 − |x + y| − |y − x|, x, y ∈
[−15, 15] × [−15, 15].
3. Graph the following 3D surfaces. For each of these, have the titles specify the
problem number and part, and have the axes labeled.
(a) z = x3 y − xy3 , x, y ∈ [−5, 5] × [−5, 5] (dog saddle). Use surf.
(b) z = cos(x − y), x, y ∈ [−2π, 2π] × [−2π, 2π]. Use mesh.
(c) z = ex cos(y), x ∈ [0, 3], y ∈ [−3π, 3π]. Your choice of mesh or surf.
(d) z = cos x − cos y, x, y ∈ [−10, 10] × [−10, 10] our choice of mesh or surf.
(e) Graph the level curves (contour lines) for z = cos(x − y), x, y ∈ [−10, 10] ×
[−10, 10].
4. Consider the 3D parametric surface that is known as the Möbius strip.
m(u, v) = (7 + v cos(u)) cos(2u), (7 + v cos(u)) sin(2u), (v sin(u)
for (u, v) ∈ [0, 2π] × [−1, 1]. All graphs should have their domains defined appro-
priately so there are enough points, but not too many points. All axes should be
labeled appropriately.
(a) Graph the strip m using mesh. Make the z-axis from −2 to 2.
(b) Note that if we fix one of the variables u or v, the result is a vector function
or space curve. Add graphs of the “edges” of the strip by creating two space
curves; one when v = 1 and the other when v = −1. Plot the first curve
black and the second in white. How many edges does the strip have?
(c) Add graphs of space curves when v = 0 and v = 0.5, the first as blue and the
second as red.
(d) Graph just the space curves from parts (b) and (c).
(e) Consider a general Möbius strip
m(u, v) = (a + bv cos(u)) cos(2u), (a + bv cos(u)) sin(2u), (bv sin(u)
for (u, v) ∈ [0, 2π] × [−1, 1]. The strip above is when a = 7 and b = 1. Graph
the strip for different values of a and b. What changes about the strip when
we change those values? What happens if we change the domain for v to
[−5, 5]?
5. Graph the following 3D surfaces. For each of these, have the titles specify the
problem number and part, and have the axes labeled.
(a) z = sin(x − y), x, y ∈ [−π, π] × [−2π, 2π]. Use surf and the default number
of elements when defining your domain.
Three-Dimensional Plots 81
(b) z = sin(x − y), x, y ∈ [−π, π ] × [−2π, 2π ]. Use surf and when defining your
domain, use fewer than the default to get a decent, yet not jagged, graph.
(c) Graph the level curves (contour lines) for z = sin(x − y), x, y ∈ [−10, 10] ×
[−10, 10].
6. Graph the function
2π x 2π y
f (x, y) = x cos cos , x ∈ [0, 150], y ∈ [0, 100].
50 50
Create the plots using mesh, surf and create a level curve (contour plot) of f (x, y)
and display all three of them side-by-side using subplot. Explain on paper what
the difference between mesh and surf are, which you prefer, and why. Make sure
each of the axes are labeled and each plot has an appropriate title.
7. Graph the function f and a contour plot of the function
2π x 3π y
f (x, y) = sin sin
60 60
in the domain x ∈ [0, 100] and y ∈ [0, 100]. Graph the plots side-by-side.
8. Use the sphere and surf commands to create a sphere of radius 4, centered at
the point (−2, 3, 5). Also, make the sphere a color of your choice.
9. Use the cylinder and mesh commands to create a cylinder of radius 5, height 7
and with axis at the vertical line with x = −2 and y = 3.
10. Make the above cylinder horizontal.
11. Create a solid of revolution such as one would see in integral calculus. First, graph
f (x) = x|sin(x)| + 4 from x = 1 to x = 8. We will create a solid of revolution by
rotating it about the x-axis. Similar to Fig. 4.24, use the cylinder command and
mesh to create this solid so that it is horizontal and the x-values go from 1 to 8.
Label the axes appropriately.
12. Consider the surface xeyz = 1 at the point (1, −1).
(a) Find the tangent plane and normal line at that point.
(b) Graph the surface, tangent plane, and normal line. For the surface and plane,
the domains should be x, y ∈ [0.5, 1.5] × [−1.5, −0.5]. The domain for the
line should be t ∈ [−1, 1]. Make sure your domains are defined appropri-
ately to be able to see the picture, and modify the aspect ratio to see the
orthogonality of the line with the surface. Have the line in black, the surface
z = f (x, y) be one color, and the plane be another. The use of the command
alpha and/or view may be useful to get a decent figure.
CHAPTER 5
Functions
5.1. The lookfor and help commands
The command lookfor is a useful command when you think there may be a command
with a certain name, or that performs a certain function.
Once you know the command name, you can use the help command as discussed
previously.
MATLAB® help and lookfor commands will search both the native MATLAB
functions but also functions within the current folder or directory.
function header
% H1 LINE
% HELP LINE(S)
BODY
end % end line not always necessary, but useful for clarity
function y = fexample1(x)
% Evaluates x^(1/3).
y = x^(1/3);
end
function y = fexample2(x)
% FEXAMPLE2(X) Evaluates x^(1/3).
% X can be a number, vector or matrix.
y = x.^(1/3);
end
If we use the lookfor command, it will not give use fexample1 since the H1
line does not contain the function name, while both would be returned when we
lookfor evaluates.
HELP LINES are SUBSEQUENT COMMENT LINES without any breaks. The
lines, in addition to the H1 lines, appear as the text when using help and should be a
more detailed description of the function and its usage including what the input(s) and
output(s) are. Using the MATLAB format, any reference to the FUNCTIONNAME
and INPUT(S), OUTPUT(S) should be capitalized in the comments for formatting
purposes though in reality they are not capitalized when used. Note that by formatting
your help lines this way, in recent versions of MATLAB the capitalized function name
appears in lowercase bold in the command window.
To create paragraphs within help, have a line with only the comment symbol. An
actually blank line will break the help comment block and the next comment is then
not considered part of the help.
function A = fexample3(x,y)
% FEXAMPLE3(X,Y) evaluates X^Y for the input numbers or vectors X, Y.
%
% See also FEXAMPLE1, FEXAMPLE2.
% LAO
A = x.^y;
end
What follows is the main block of the function that includes commands and com-
ments. The function file can be with our without an end. The end is necessary for
nested functions, or multiple functions in one file.
86 Programming Mathematics Using MATLAB®
function y = fexample1(x)
% Evaluates x^(1/3).
y = x^(1/3);
end
The writing of fexample1 could be improved. The HELP lines could include the
function name, and it could be written so x could be a vector or matrix (if so desired).
The improvement is seen in fexample2 below.
function y = fexample2(x)
% FEXAMPLE2(X) Evaluates X^(1/3).
% X can be a number, vector or matrix.
y = x.^(1/3);
end
function A = fexample3(x,y)
% FEXAMPLE3(X,Y) evaluates X^Y
% for the inputs (numbers or matrices) X and Y.
%
% See also FEXAMPLE1, FEXAMPLE2.
% LAO
A = x.^y;
end
r1 = (-b-sqrt(d))/(2*a);
r2 = (-b+sqrt(d))/(2*a);
r1 = (-b-sqrt(d))/(2*a);
r2 = (-b+sqrt(d))/(2*a);
R=[r1; r2];
Note that the above functions do not have end. As mentioned above, this is not nec-
essary if there are not nested or multiple functions within the same file. One may
argue that it is good practice to still include them. Also note that in quadratic2, the
one output variable name is in brackets. This is not necessary; the functionality would
be the same if the output variable name appeared without the brackets (as it does in
fexample1.
The real difference in these functions is how the output variable(s) are defined and
thus how we must use the functions correctly.
>> quadratic1(1,3,2)
ans =
-2
88 Programming Mathematics Using MATLAB®
>> quadratic2(1,3,2)
ans =
-2
-1
Note for quadratic1, only the first output variable is displayed and stored in ans,
while for quadratic2, both solutions are displayed and stored in ans as a (column)
vector. We could also store the output as a row vector as in quadratic2b.
r1 = (-b-sqrt(d))/(2*a);
r2 = (-b+sqrt(d))/(2*a);
R=[r1, r2];
>> quadratic2b(1,3,2)
ans =
-2 -1
The issue with the way these functions are written is that the user needs to know
how the outputs are going to be displayed in order to use them correctly for anything
useful. See the example below.
>> [x1,x2]=quadratic1(1,3,2)
x1 =
-2
x2 =
-1
>> [x1,x2]=quadratic2(1,3,2)
Error using quadratic2
Too many output arguments.
>> X=quadratic1(1,3,2)
X =
-2
>> [X]=quadratic1(1,3,2)
X =
-2
>> X=quadratic2(1,3,2)
Functions 89
X =
-2
-1
Examples of how to improve these functions are shown in the following chapter
once conditional statements are discussed.
function y = badfunction1(x)
% FCNEX1 Evaluates the cube root of a number X.
% LAO
x^(1/3)
>> badfunction1(8)
ans =
2
function Y = badfunction2(x)
% BADFUNCTION2 Evaluates the cube root of a number X.
% LAO
Y = x^(1/3)
end
Again, you may be able to figure out the errors by seeing the function in use.
>> badfunction2(8)
Y =
2
ans =
2
90 Programming Mathematics Using MATLAB®
5.4. Exercises
√
x5 2x + 3
1. Write a function named ch5prob1 for the function f (x) = 2 . The input of
(x + 1)3
the function should be x and the output should be the calculated value f (x). Write
the function so that x can be a number, vector, or matrix just as the sin function
works.
2. Consider the function
1 −1· x−μ 2
f (x) = √ e 2 σ
.
σ 2π
(a) Create a function called npdf that takes as input x, μ, and σ . It then calculates
y = f (x), making sure that the calculations can be done if x is a number,
vector or matrix, just as the sin function works (σ and μ are numbers and it
is assumed the user will do this correctly; no error checking is done on this).
(b) For μ = 0 and σ = 1, graph y = f (x) for x ∈ [−5, 5].
(c) Graph the following two plots on the same figure. The first should be of
y = f (x) for x ∈ [130, 170], μ = 150.24, and σ = 8.44. The second should be
for y = f (x) for x ∈ [130, 170], μ = 153.07, and σ = 9.24. Have a legend for
this, with the first plot having the title “Verbal Reasoning” and the second
plot having the title “Quantitative Reasoning”. The overall title should be
“GRE Test Scores July 1, 2015 to June 30, 2018” [5, p. 18].
3. Consider the function
− ν+2 1
ν+2 1 t2
f (t) = √ 1+
νπ ν2 ν
(a) Create a function called tpdf that takes as input t and ν and computes y =
f (t) making sure that the calculations can be done if t is a number, vector or
matrix, just as the sin function works (no error checking is done on ν ).
(b) Perform the command help tpdf.
(c) Use your function to graph y = f (t) for t ∈ [−4, 4] and ν = 1.
(d) Use your function to graph the following three plots on the same figure.
They should all be for t ∈ [−4, 4]. The first plot should be with ν = 1, the
second with ν = 2, and the third with ν = 5. Have all be different colors and
have a legend for the plots. The Greek letter ν can be written in text as “\nu”
in MATLAB.
Functions 91
(c) x2 − 100,000,000x + 1 = 0.
6. Recall that polar coordinates (r , θ ) can be converted to Cartesian coordinates (x, y)
with the equations
x = r cos θ,
y = r sin θ.
Consider the family of curves given by r = 1 + c sin(nθ ), where c is any real number
and n is a positive integer. Write a function file called pcurves that takes as input
n, c and θ where θ can be either a number or vector, n is a positive integer and c
is any real number (no need to have error checks). The outputs should be the x
and y values. Then, using your function, graph the curves (in the Cartesian (x, y)
coordinate system) using subplot and varying n and c to answer the following
questions. Be sure to label your graphs appropriately.
(a) How do the graphs change as n increases?
(b) How do the graphs change as c changes?
7. Elementary row functions For the following functions, make sure the help lines
make it clear not only what the function does, but what the inputs are and in what
order they should be.
92 Programming Mathematics Using MATLAB®
(a) Create a function called swap that performs the first elementary row function
on a matrix. The inputs should be A,i,j and the function should return a
matrix B that is the same as A except the ith and jth rows are swapped.
(b) Create a function called multrow that performs the second elementary row
function on a matrix. The inputs should be A,r,i and the function should
return a matrix B that is the same as A except the ith row of A is multiplied
by r.
(c) Create a function called addrow that performs the third elementary row
function on a matrix. The inputs should be A,r,i,j and the function should
return a matrix B that is the same as A except r times the ith row of A is added
to the jth row.
8. You want to create multiple versions of homework and exam problems quickly.
For example, you want to create homework problems with different coefficients of
polynomials and you will use MATLAB to generate these coefficients. MATLAB
has ways to create random numbers, but we want specific constraints and we may
modify these constraints for different problems, so we will create functions to use
repeatedly. The help lines for these functions should be very clear on how to use
these functions. In Exercise 10 in Chapter 6 we will expand on these functions.
(a) Create a function randInt2 that takes as inputs 2 integers, a and b. The
function generates a random integer from a to b. No error checking will be
done on the inputs a and b; we will assume the user inputs integers a < b.
(Error checks will be created in Exercise 10 in Chapter 6.)
(b) Create a function randList that takes as input a vector of numbers (do not
do any error checking on this; assume a vector is correctly input by the user).
The function will return a random element from the vector (list).
CHAPTER 6
Control Flow
6.1. Relational and logical operators
Relational and logical operators allow one to compare two values, variables, etc. The
operators take on the form expression1 OPERATOR expression2 and evaluate to a logical
data type; either true (1) or false (0).
Relational operators
You can use relational operators on vectors to compare to other vector(s) of the same
size. The comparison is made component-wise and returns a vector of the same size
with each entry either true or false (see Table 6.1).
>> 1 < 2
ans =
logical
1
>> 1 > 2
ans =
logical
0
>> 6/3 == 2
ans =
logical
1
>> 1 == sin(pi)
ans =
logical
0
>> A=randi([0,5],1,5), B=randi([-5,5],1,5)
A =
4 1 3 4 5
B =
5 1 -4 -4 -3
>> A <= B
ans =
1×5 logical array
1 1 0 0 0
>> A == B
ans =
1×5 logical array
0 1 0 0 0
>> A ~= B
ans =
1×5 logical array
1 0 1 1 1
Likewise, you can use relational operators to compare matrices of the same size.
Logical operators
Logical operators can be used to create compound statements that evaluate to either
true or false (see Table 6.2).
Eager versions will evaluate both expressions no matter what. The short-circuit
versions are only good on scalars and will only evaluate the second expression
if needed. Pros and cons to using each version are more apparent in complicated
programs. For a discussion on the topic, search “short-circuit evaluation” on Wikipedia.
>> z=-exp(1), w = pi
z =
-2.7183
w =
3.1416
>> z > 0 && w > 0
ans =
logical
0
>> z > 0 || w > 0
ans =
logical
1
>> z > 0 & w > 0
ans =
logical
0
>> z > 0 | w > 0
ans =
logical
1
The eager versions of the logical operators produce matrices of 0s and 1s if one of
the arguments is a matrix.
ans =
2×3 logical array
0 0 0
0 0 1
>> (X > Y) | (Y < 1)
ans =
2×3 logical array
1 1 1
0 0 1
>> xor(X > 0, Y > 0)
ans =
2×3 logical array
0 0 0
0 1 1
The any and all operators are useful, and work on vectors or on the columns of a
matrix.
Note how any and all work column-wise or over all elements on matrices.
>> any(Y == 5, 2)
ans =
Control Flow 97
Also note where the operators fall under the order of precedence (see Table 6.3).
6.2. If statements
Flow control in the form of if statements is vital for programming. MATLAB® has if,
if-else, and if-elseif-else statements. These statements can be nested. Notice
that there is no begin in these statements, but there must be an end.
If statements have the following pattern:
a=5; b=-2;
if b ~= 0 && (a == 5 || a == 3)
yy = a/b;
zz=a+b;
disp('hi!')
end
function y = ispos(n)
% ISPOS(N) returns true if N is positive, false otherwise.
if n > 0
y = true;
else
y = false;
end
end
Example 6.2.1. Use an if-else statement to define a function for the following
piecewise function:
2x − 5 x > 3,
f (x) =
x2 − 8 x ≤ 3.
function f = pwexample(x)
% PWEXAMPLE(X) demonstrates an if-else statement for piecewise function.
if x > 3
f = 2*x - 5;
else
f = x^2 - 8;
end
NOTE: the above example will not work if x is a vector or matrix, even if component-
wise calculations are used. See Example 6.4.1 on how to accommodate this.
if x < 0
s = -1;
else
if x > 0
s = 1;
else
s = 0;
end
end
Nested statements such as the one above are common in other languages. In MAT-
LAB as in some other languages, one can instead take advantage of if-elseif-else
statements to accomplish the same thing but more efficiently.
Control Flow 99
if x < 0
s = -1;
elseif x > 0
s = 1;
else
s = 0;
end
6.3. Switch/case
The switch command is an alternative to using nested statements or if-else-elseif state-
ments in some cases. Switch tests against the equality of an expression against certain
value(s). Switch statements work best against a discrete set of values, while in the case of
the piecewise function example with inequalities, one would still need an if-statement.
switch x
case {-1, 0, 1}
y = 3;
case {-2, 2}
y = 5;
otherwise
y = 7;
end
Because the logical true is also 1, and logical false is 0 within MATLAB, we can easily
create characteristic functions that can be implemented to create piecewise functions
without if-statements, among other things. Consider the following example.
Example 6.4.1. Rewrite the piecewise function in Example 6.2.1 with the use of a
characteristic function.
function f = pwexample2(x)
% PWEXAMPLE3(X) demonstrates an characteristic function to create a
% piecewise function.
% This function will work if X is a vector or matrix.
end
The expression is usually a vector defined with the colon operator or explicitly defined.
It can also be a matrix, but note that implementation is done one column at a time.
Consider the following function, myscatter, which creates n random points (x, y)
and plots each one.
function myscatter(n)
% MYSCATTER Example of using a for loop to create a scatter plot.
% MYSCATTER(N) creates a plot of N points that are randomly generated.
x=rand(1);
y=rand(1);
plot(x,y, '*', 'MarkerSize',8)
hold on
for k=2:n
x=rand(1);
y=rand(1);
plot(x,y, '*', 'MarkerSize',8)
end
hold off
end
Control Flow 101
Note that this is not the most efficient way of doing this within MATLAB. First, there
is already a scatter plot command and secondly, we can make the above code more
efficient by what is called VECTORIZING THE CODE, which we will discuss later.
Another common use of a for loop is for calculating sums.
function s = geomseries(r, n)
% GEOMSERIES computes the sum of the geometric sequence
% Y = GEOMSERIES(R,N) is the sum of R^k from k=0 to k=N.
s = 0;
for k=0:n
s = s + r^k;
end
end
The following example shows how to use nested for-loops to work with matrices.
Example 6.5.1. Improve the previous function in Example 6.2.1 so that it also works
if x is a vector or matrix with the use of if-statements and nested for-loops.
2x − 5 x > 3,
f (x) =
x2 − 8 x ≤ 3.
function f = pwexample3(x)
f = 0*x;
[rows,cols] = size(x);
for j = 1:rows
for k = 1:cols
if x(j,k) > 3
f(j,k) = 2*x(j,k) - 5;
else
f(j,k) = x(j,k)^2 - 8;
end
end
end
We saw in Example 6.4.1 that this longer code is not necessary with the use of
characteristic functions, but there are many examples why nested for loops would be
necessary. For example, if the index of the matrix entry is needed, or in the case of
double (triple, etc.) summations.
The colon operator can be used to have the for loop increment backwards, or you
can explicitly state the values as seen in the examples below.
102 Programming Mathematics Using MATLAB®
for k = 10:-1:1
disp(k)
pause(1)
end
disp('Blast off!')
%% different increment
for k = 2:2:8
disp(k)
pause(0.5)
end
disp('Who do we appreciate?')
%% using defined vector
x = [2 4 6 8];
for k = x
disp(k)
pause(0.5)
end
disp('Who do we appreciate?')
The following example shows how the for loop works with matrices. Run the code
to see the results. Note that the results within the loop are displayed for demonstration
purposes.
x=[2 6; 4 8];
for k=x
disp(k)
pause(0.5)
end
disp('Who do we appreciate?')
%% showing the matrix implementation
x
for k=x
k
sumk = sum(k)
maxk = max(k)
end
while EXPRESSION
STATEMENT(S) OR COMMAND(S)
end
Control Flow 103
The statements or commands within the loop are executed as long as the expression
is true. This can mean that until something with expression changes, the loop may
become an infinite loop.
You can use while loops to generate better data, or continue to ask the user until a
valid answer is submitted.
While loops are also useful in working with tolerance checks. In general, the dif-
ference between while loops and for loops is with for loops, the number of times to
loop through is known, and with while loops, you want to keep doing something until
something changes.
%% break example
clc
for k=1:5
if k==3
break
disp('ah ha!')
end
disp(k)
end
%% continue example
clc
for k=1:5
if k==3
continue
104 Programming Mathematics Using MATLAB®
disp('ah ha!')
end
disp(k)
end
The return command is useful for script or function files, in which the command
acts like an end to the function, or “end of file” of the script file.
The error command is useful in which you can develop meaningful error messages
to the user. One can accomplish a similar task using disp or even fprintf (more on
that command later) along with return, but error is more efficient and the error
message is automatically displayed in red similar to MATLAB errors.
>> A
A =
1 2 3
4 5 6
>> size(A) % no output specified
ans =
2 3
>> y = size(A) % one output specified
y =
2 3
>> [r, c] = size(A) % two outputs specified
r =
2
c =
3
The following function quadratic4 was written to display or store the outputs
similar to the size command but for the quadratic function.
Control Flow 105
r1 = (-b-sqrt(d))/(2*a);
r2 = (-b+sqrt(d))/(2*a);
if nargout < 2
r1 = [r1, r2];
end
end
d = b^2-4*a*c;
r1 = (-b-sqrt(d))/(2*a);
r2 = (-b+sqrt(d))/(2*a);
if nargout < 2
r1 = [r1, r2];
end
end
106 Programming Mathematics Using MATLAB®
The variables varargin and varargout are cell arrays of variable input or output
arguments. The quadratic6 function demonstrates the use of varargin to function
similarly to quadratic5.
d = b^2-4*a*c;
r1 = (-b-sqrt(d))/(2*a);
r2 = (-b+sqrt(d))/(2*a);
if nargout < 2
r1 = [r1, r2];
end
end
The function mySquare demonstrates another nice use for varargin. This function
allows for optional LineSpec (line style, marker symbol, and color).
function mySquare(s,x,y,varargin)
% MYSQUARE plots a square with length S with lower left corner at X,Y
% MYSQUARE(S,X,Y) or MYSQUARE(S,X,Y, LINESPEC)
plot([x,x+s,x+s,x,x],[y,y,y+s,y+s,y],varargin{:})
function y=myRandN(mu,sigma,varargin)
% MYEXAMPLE demonstrates using nargin and vargin
switch nargin
case 2
Control Flow 107
y=randn*sigma + mu;
case 3
y=sigma*randn(varargin{1}) + mu;
case 4
y = sigma*randn(varargin{1},varargin{2}) + mu;
end
end
6.9. Exercises
√
x3 2x + 3
1. Write a function named hw6prob1 for the function f (x) = that does
(x4 + 1)3
the following:
• The input of the function should be x and the output should be the computed
value y = f (x).
• Write the function so that x can be a number, vector or matrix.
• Using the any and/or all logical operators, first test within the function to
make sure that all of the values of x are valid for R-valued calculations. If not,
an appropriate error message is displayed using the error command.
• You should test your calculations with at least 4 different inputs. Write down
the input tests you used, along with the answers that your function gives you.
2. Create a function called isZ that will take one input and output a logical true
or false (value of either 0 or 1 specifying false or true, respectively). If the input
is an integer (NOT TALKING ABOUT DATA TYPE INTEGER – meaning
it is not π , or not 3/2, etc.), then it will return a logical true, otherwise it will
return a logical false. Note that this should still work if the input is a vector or
matrix, and would return a vector or matrix of true/false based on whether each
entry/component is an integer or not. Run tests of the function. This function
should be used on any subsequent problem that needs to check if a variable or
input is an integer.
3. Create a function called isEven that will have one input that is supposed to be
an integer. First check whether the input is an integer; if not, use the error
command to display an appropriate error message. The function should return a
logical true if the input is even, and a logical false if it is odd. Run tests of the
function.
4. Finish the function plotVec that is found on the text website. This function has
one or more inputs and uses varargin. The first input is P, which is a column
vector with two or three rows (check for it: if not, return an error). The function
will take the column vector and plot the vector as a line segment from the origin
to the given point (from the input P). Any other input arguments are optional and
specify how the vector will be drawn (color, line width, marker type, etc.). The
108 Programming Mathematics Using MATLAB®
function will not have an output (it will only create a plot). Hint: remember the
difference between plot and plot3! Run it once for a 2D point and another time
for a 3D opint, using your choice of plot specifications (or none) on each.
BONUS: create a function plotVec2 that will expand on plotVec. This function
will take a MATRIX of 2D or 3D points and connect them all, in order. Thus it
could create a polygon from the matrix in which each column is a vertex of the
polygon. Discuss the limitations or difficulties this may have in coding it and/or
implementation.
5. Finish the function plotPlane that is found on the text website. This function
has two or more inputs and uses varagin. The first input is M which is a matrix
that has exactly three rows and at least two columns (check for it; if not, return
an error). The second input ax determines the domain for the plane; the domain
will be from -ax and ax (Hint: remember meshgrid!) Any other optional inputs
will specify EdgeColor, etc. to plot the plane using the mesh command. Use the
function to plot a plane using M =randi; create M, display it and then use your
function to plot the plane.
6. Create a new function called parity that does the following:
⎧
⎪
⎪
⎨1 x is even,
f (x) = 0 x is odd,
⎪
⎪
⎩ −1 x is not an integer.
x = r cos(θ ) + h
y = r sin(θ ) + k
for θ ∈ [0, 2π ]. Create a function myCircle that takes as inputs a positive number
r, a 2D point (vector) C, and an optional positive integer n. Error checking should
be done on r, C (and n if input) and appropriate messages displayed using the
error command. This function will output vectors x and y of size n (with default
value of n = 100) that are the calculated parametric equations for a circle with
radius r with center C (h, k). Have the output be similar to size or quadratic4
(page 105) in that both are output regardless of how the user runs the function.
(a) Use your function to plot the unit circle and another circle with radius 3
and center (−2, 4).
(b) Create another graph where you plot the unit circle but with no input for
n, n = 4, n = 5, and n = 9.
The command axis equal may come in handy for these plots!
10. We will expand on the Problem 8 in Chapter 5.
(a) Create a function randInt.m that takes as inputs two OR three arguments.
If the two arguments a and b are input, then the function generates a random
110 Programming Mathematics Using MATLAB®
integer from a to b. If the three arguments a, b, and c are input, the function
generates a random number from a to b with an increment of c. So if I
input randInt(-5,5) it would give me a random integer (NOT data type
integer!) from −5 to 5. But if I input randInt(-5,5,.5) it would give me
a random number from the list −5, −4.5, −4, −3.5, . . . , 4, 4.5, 5. ERROR
CHECK: check to make sure a < b and (if input) c > 0. If either of these
errors occur, use the error command to stop the function and output an
appropriate error message.
(b) Create a function nonzeroRand.m that takes as inputs two OR three argu-
ments. If the two arguments a and b are input, then the function generates a
random NON-ZERO INTEGER from a to b. If the three arguments a, b,
and c are input, the function generates a random NON-ZERO NUMBER
from a to b with an increment of c. You will use a WHILE loop within this
function. ERROR CHECK: check to make sure a < b and (if input) c > 0.
If either of these occur, use the error command to stop the function and
output an appropriate error message.
11. You are creating a multiple choice problem in which students will be asked to
solve ax + b = cx + d for x, where a, b, c, and d are certain random integers. You
have decided that the wrong answers given in the problem are:
Initially, the problem is set such that a is a random integer between 2 and 6, b is
a non-zero random integer between −4 and 4, c is a random integer between 3
and 7, and d = a + b − c − 1. The problem is set that if c = a or a = c + 1, a new c is
generated until both c = a and a = c + 1. The problem is also set that if b = d, a new
b is generated (and thus d) until b = d. (Think: why would we want this check?
Unfortunately, you notice that there are times that some coefficient combinations
make it so there are duplicate answers listed in the multiple choice problem. You
already realize there are issues when the denominators and/or numerators equal
zero but those are already taken care of; you need to find the other bad combina-
tions. Instead of trying to figure out algebraically how to define the coefficients so
this does not happen, you write a MATLAB script called algProblem.m to help
pinpoint what combination(s) of coefficients will and will not work.)
(a) What is the correct answer to the problem in terms of a, b, c, and d? Show
all work on paper.
(b) Create a script file algProblem that does the following:
• Initialize vectors A, B, and C to contain all of the possibilities of values
for a, b, and c, respectively.
Control Flow 111
all four values of the coefficients and output that vector; also create a
vector Answers that has the multiple choice answers and output that
vector.
(c) How many bad combinations of coefficients are there? What are they? State
your answer on your paper and list the bad combinations of coefficients
clearly. No need to show your work on this one; I should be able to run
your script to see the work. Do not run the script file within the homework
file.
12. Create a new function called mysgn that is a variation on the signum function:
⎧
⎪
⎪
⎨1 x > 0,
sgn(x) = 0 x = 0,
⎪
⎪
⎩−1 x < 0.
Notice if you copy the above fprintf command and run it, the command prompt
and cursor is at the end of the text, which is difficult to see. To get a new line, use “\n”.
A tab is “\t”.
Notice the “placeholders” for where the variables go in the text. These are using
formats.
Here is e: 2.72
Here is e: 2.7183
Further explanations of the above formatting can be found in the MATLAB® doc-
umentation.
The formatting in the fprintf does not pay attention to the formatting you have
set outside of the command (see the section below for a table of formats):
ans =
2.72
Here is e: 2.718282
some text: 7
some text:1024
>> fprintf('%-2.0f\n%-2.0f\n\n',7,2^10)
7
1024
some text:7
some text:1024
Another nice format is using “%g” which will use either %f or %e, whichever is the
shortest:
a=10;
b=34/(2*pi);
plottitle=sprintf('Helix with a=%i and b approximately %3.5f',a,b);
t=linspace(0,100,750);
x=10*cos(t);
y=10*sin(t);
z=b*t;
plot3(x,y,z)
title(plottitle)
>> n=101;
>> errormsg = sprintf('We need n to be even. You entered n = %i',n);
>> if mod(n,2)~=0
error(errormsg)
end
We need n to be even. You entered n = 101
>> x=10*pi
x =
31.42
>> format
>> x
x =
31.4159
>> save('saveddata1.mat')
Then one can load that file at any other time to retrieve the data.
>> load('saveddata1.mat')
>> tic
>> n=0
n =
0.0000e+000
>> for k=1:10000
n=n+n^2;
end
>> toc
Elapsed time is 12.720630 seconds.
Notice the above is also the time it took to type those commands into the command
window.
% First example
color1 = [0,0.4470,0.7410]; % default first color starting in version 2014a
x=linspace(-3,3);
fill(x,sin(pi*x),color1)
% Second example
t=linspace(0,2*pi);
xc = cos(t); yc = sin(t);
fill(xc,yc,color1)
If x and y are defined with x=linspace(-2,2); y=x.^2; you get Fig. 7.3(A)
using fill(x,y,color1). For regions such as “area under the curve”, you will need
to adjust the points. Using fill([-2,x,2],[0,y,0],color1) on the same x and y
leads to Fig. 7.3(B).
120 Programming Mathematics Using MATLAB®
Figure 7.2 Examples of fill command. (A) Filling y = sin(π x ), (B) Filling a circle.
Figure 7.3 Adjusting to get the area under the curve. (A) Fill y = x 2 , (B) Adding points to adjust.
Here follows another example of “area under the curve” that created Fig. 7.4.
For basic regions between two functions, one can do the following to create Fig. 7.5.
Notice the use of the useful command fliplr(x) which creates a vector that has the
values of x but in reverse order.
Miscellaneous Commands and Code Improvement 121
x=linspace(-pi,pi);
y=cos(x);
x2=fliplr(x);
y2=-sin(x2)-3;
fill([x,x2],[y,y2],color2)
hold off
axis equal
ax=1.2;
axis([-ax,ax,-ax,ax])
plot(xsine,ysine)
hold on
fill(xtriangle,ytriangle,'y')
hold off
If we reorder the commands as in the following code, the sine wave is then plotted
“on top” of the filled triangle, as shown in Fig. 7.7(B).
For certain plotting commands, the alpha(n) command can create transparency.
The value n is a number between 0 and 1, with 1 being opaque, and 0 being completely
transparent. (Experiment!) Thus a combination of the order of the commands and the
use of alpha can give you more control over the look of the figure (see Fig. 7.8).
plot(xsine,ysine,'k')
hold on
Miscellaneous Commands and Code Improvement 123
fill(xtriangle,ytriangle,'g')
alpha(0.3)
hold off
axis equal
Figure 7.7 The order of plot and fill commands matter. (A) Plot first, then fill, (B) Fill first, then plot.
Note that the alpha command will apply to all commands that appear before it; thus
you can control which objects get transparency by the order of the alpha and plotting
commands, as shown in Fig. 7.9 below.
fill(xtriangle,ytriangle,'g');
hold on
fill(xcircle,ycircle,'r');
alpha(0.2)
124 Programming Mathematics Using MATLAB®
fill(xsine,ysine,'b');
hold off
axis equal
You can also define different alpha to specific commands, or apply alpha to only one
as the following code demonstrated in Fig. 7.10.
f1=fill(xtriangle,ytriangle,'g');
hold on
f2=fill(xcircle,ycircle,'r');
f3=fill(xsine,ysine,'b');
alpha(f3,0.4)
alpha(f2,0.7)
hold off
axis equal
>> syms x
>> f(x) = sin(pi*x)
f(x) =
sin(pi*x)
>> f(1)
ans =
0
>> A=f([0, 1/6, 1/4, 1/3, 1/2])
A =
[ 0, 1/2, 2^(1/2)/2, 3^(1/2)/2, 1]
>> double(A) % this will give numeric approximations to A
ans =
0 0.5000 0.7071 0.8660 1.0000
If you already have a string defined that we want to turn into a symbolic function,
one can use the str2sym command for MATLAB R2017b or later. Otherwise one
should use the evalin command. Other ways generate warnings and errors. Note that
component-wise operations are not needed.
>> syms x y
>> g(x)=x^3*sin(x);
>> t=linspace(-10,10);
>> plot(t,g(t))
>> expand((x+y)^3)
ans =
x^3 + 3*x^2*y + 3*x*y^2 + y^3
>> factor(x^2 + x*y -2*y^2)
ans =
[ x - y, x + 2*y]
>> syms x
>> f(x)=sin(pi*x) + exp(x);
>> g(x)=25*x^4;
>> df = diff(f)
df(x) =
exp(x) + pi*cos(pi*x)
>> dg = diff(g,x)
dg(x) =
100*x^3
>> dg(-1)
ans =
-100
>> syms t
>> h(x,t) = t^2 - 5*t*x + x^3
h(x, t) =
t^2 - 5*t*x + x^3
>> dhdt = diff(h,t)
dhdt(x, t) =
2*t - 5*x
Similarly, the int command can be used for integrals, both definite and indefinite.
>> f,g,h
f(x) =
sin(pi*x) + exp(x)
g(x) =
25*x^4
h(x, t) =
t^2 - 5*t*x + x^3
>> int(f)
ans(x) =
exp(x) - cos(pi*x)/pi
>> int(g,1,2)
ans =
155
Miscellaneous Commands and Code Improvement 127
The command conv (short for convolution) will do the appropriate algebra on
vectors that is equivalent to multiplication of polynomials. Note that for conv the vec-
tors do not need to be of the same size. The command deconv will perform polynomial
division.
ans =
1 -3
The polyder and polyint commands will return vectors that are the coefficients
for the derivatives and integrals, respectively, of the polynomials/vectors.
The command polyval evaluates the given polynomial at the indicated value.
The roots command should be self-explanatory, but realize that it will also return
complex roots.
The command polyfit(x,y,n) will try and fit (using least-squares) the input data
(x, y) to a polynomial of degree n as the following example demonstrates.
Example 7.1.1. Fit the points (0, 0), (−1, 1), and (2, −2) to a line. State the line and
plot the data points and line.
We can use polyfit with n = 1 for a line.
hold on
plot(xplot,yplot,'k')
hold off
p =
-0.642857142857143 0.214285714285714
and this line and these points are shown in Fig. 7.11.
Fig. 7.12 demonstrates the results of polyfit using polynomials of different degrees
on x=0.5; y=x.∗cos(x).∗exp(x).
science course and we will not go into details about this here. Many of our exercises in
this course will not warrant this type of detail.
This section will focus on two basic methods of code improvement that may not be
available in other languages: vectorization of code, and preallocation.
Example 7.2.1. Calculate the geometric series the traditional way and using vector-
ization of code and compare using the tic and toc commands.
% Traditional way
tic
s1=0;
for k=0:n
s1=s1+r^k;
end
t1 = toc;
% Vectorization of code
tic
k=0:n;
s2=sum(r.^k);
t2 = toc;
end
Now look at the difference in times. For various values of n, we now run the
following code.
[t1,t2]=geomseries2(0.5,n);
fprintf('\nThe two times for n = \%i are: \n\ttime1 = \%2.5f and \n\ttime2 = \%2.5f\n
\n', n, t1, t2);
>>
7.2.2 Preallocation
One can make programs more efficient by preallocating the size of large vectors or
matrices rather than appending. For example, if you have a recursive algorithm, you
can preallocate a vector or matrix for the number of entries needed to complete the
algorithm. Again, explanation will be by example.
132 Programming Mathematics Using MATLAB®
function F = Preallocation(n)
% PREALLOCATION(N) demonstrates the efficiency of preallocation.
% PREALLOCATION(N) calculates the first N Fibonacci numbers.
% Traditional way.
F1=[1 1];
tic
for k=3:n
nextOne = F1(k-1) + F1(k-2);
F1 = [F1 nextOne];
end
toc
% Preallocation
tic
F2=ones(1,n);
for k=3:n
F2(k) = F2(k-1) + F2(k-2);
end
toc
F = F2;
• Rotation by an angle θ about the origin O where the rotation is measured from
the positive x-axis (see Fig. 8.2) can be represented as:
x1 cos θ − sin θ x1
T = .
x2 sin θ cos θ x2
• Reflection about a line through the origin, where θ is the angle from the positive
x-axis to is given by
cos 2θ sin 2θ a b
A= = , a2 + b2 = 1.
sin 2θ − cos 2θ b −a
Transformations and Fern Fractals 137
x −1 0 x
T =
y 0 1 y
If you think about some transformations that are performed after each other, the or-
der in which they are done will matter. Likewise, since matrix multiplication is not
commutative, the order matters (see Fig. 8.4).
The above are examples in which the matrices have particular patterns or formats
to generate particular transformations or geometric results. Any matrix will yield a
138 Programming Mathematics Using MATLAB®
Figure 8.4 Composition example. (A) Rotation, then reflection, then dilation, (B) Dilation, then reflec-
tion, then rotation.
linear transformation; the big difference being when transforming a polygon as in our
examples, the angles between sides are not necessarily preserved and lengths of the sides
may not be scaled equally. For example, consider the linear transformation obtained
from the matrix M (see Fig. 8.5):
− 12 −2
M= 3
2 −2
T (x) = x.
These transformations preserve the lengths of the vectors and the inner or dot products.
Thus in Euclidean vector spaces, the angles between vectors are preserved in addition
to the lengths of the vectors. This means that under these linear transformations, right
triangles transform to right triangles of the same size. Contraction and dilation trans-
formations also preserve angles, but the lengths of the vectors change so right triangles
transform to similar right triangles. Other transformations will transform right triangles
to triangles, but the transformed triangles are not necessarily right triangles and the sides
are not necessarily the same length or even same proportion.
T (x) = Mx + v
One can think of affine transformations as linear transformations (Mx) then shifted
by the vector v. Similar to linear transformations, affine transformations preserve straight
lines: thus triangles remain triangles, quadrilaterals remain quadrilaterals, etc.
The example below shows examples of two affine transformations.
• Start at the origin, one of the four transformations is chosen based on its probability.
The next point is calculated based on this transformation calculated on the current
point.
• Repeat this process with each new point calculated.
For a specific IFS, the image created will resemble ferns. In order to work with the
probabilities and chosen transformations, we will split up the interval [0, 1] based on
probabilities. For example, if there are three transformations, the first having probability
0.25, the second 0.5, and the third 0.25, then we will select which transformation is
chosen by using rand to generate a number between 0 and 1. If the number is between
0 and 0.25, the first transformation is selected. If the number is between 0.25 and 0.75,
the second transformation is selected. Lastly, if the number is between 0.75 and 1, the
third transformation is selected. Which transformations get the endpoints of 0.25 and
0.75 does not really matter.
8.4. Exercises
1. Set up
(a) We will define the RGB code for four colors are as follows:
Save the MyColors.mat file found in on the text website to your folder/direc-
tory and use the load('MyColors') command to load the vectors that can
be used as colors.
(b) One of the shapes we will use in these exercises will be an ellipse made with
100 points using the parametric equations x = 2 cos(t) and y = 3 sin(t) for an
appropriate domain for t. Set up the vectors of these values (variable names of
your choice!) to plot the ellipse in this exercise and in subsequent exercises.
To test, use the plot command to plot the ellipse in mygreen with a Line
Width of 2.
2. Visualizing linear transformations
For this exercise we will be visualizing some examples of linear transformations.
The process will be the same or similar for all of them, so copy/paste will be your
friend. Remember that using the plot(x,y) command, Matlab® “connects the
dots” of the points given with x and y as vectors of the x- and y-coordinates of the
points. We will use this idea to draw shapes and the transformed shapes. One of the
shapes will be the ellipse discussed in #1b. Note that once the x and y vectors for
142 Programming Mathematics Using MATLAB®
the ellipse are created in #1b, as long as those vector names are unique you do not
need to recreate them in subsequent exercises. The other shapes will be made using
your function myCircle2 that is a (fixed) copy of the function from Exercise 9 in
Chapter 6.
Our shapes will be plotted by forming a vector comprised of the x-values and an-
other comprised of the y-values of the points that make up our shapes. Each of our
transformations will be associated with a 2 × 2 matrix A. What the matrices should
be for reflections, rotations, scaling, and compositions are in the lecture/class notes.
To visualize the transformation associated with a matrix A, we want to calculate
Av for each of the points v (which is actually a column vector) that make up our
shapes and store the answer in a new set of points. But this would be tedious and/or
inefficient to do this for each point. Instead, we can do this all at once to all of the
points by using matrix calculations. This is where it is easiest to have the original
points in a 2 × n matrix V (n is determined by the number of points that make up
our shape). If we set up the matrix V so that the first row contains the x-values of
the points, and the second row contains the y-values, then each column of V is one
point. The beauty of matrix multiplication is that T = AV will be all of the points
that make up the transformed shape. For each of the linear transformations we will
do the following.
• Formulate the vectors x, y, and matrix V that are composed of the vertices or
points of the specified original shape. Plot the original shape in mygreen with
Line Width thicker than the default.
• Figure out what the appropriate matrix A would be for the transformation,
and display that matrix. In other words, when defining the matrix for each
transformation, do not suppress the output so we can see the values in the
matrix when it is published. It may be better to have a unique name for each
transformation matrix, instead of A for each problem.
• Calculate T = AV and plot the transformed shape in the stated color with Line
Width thicker than the default.
• Plot the two stated points (markers) of the original shape in mygreen, using the
“*” marker and square marker, respectively. Plot the two transformed markers
using the same shapes, but in the same color as the transformed shape. Thus
you should be able to see where the markers went under the transformation.
• Use the command axis equal and set the axes appropriately so the edges and
points of the shapes do not touch the edge of the figure. You may have to
experiment with the order of axis equal and the command(s) to set
the axes.
• Use a legend with the titles “Original” and “Transformed” for the 2 shapes,
and “1st marker” and “2nd marker” for the specified points. Note that the
order of your plot commands will affect the order the titles should be in the
Transformations and Fern Fractals 143
legend! You may want to change the location of the legend with 'Location',
'Southeast' (or some other location specification) so you can see all of the
figures and legend. (This location may need to change for different transforma-
tions below.) For example,
legend('Sample title1', 'Sample title2', 'Location', 'Southeast').
Perform the above process for each of the following transformations and shapes.
Have the text that is in bold be the title of your figure (first example, title('
Reflection Example'))
(a) Reflection example with θ = π/6. Original shape: the ellipse. Transformed
shape in myred. First marker is the first point, the second marker is the 25th
point. Also draw the reflection line of the angle θ (easiest to use trig!) as a
black, dashed line.
(b) Scaling examples with c = 1.5 and c = 1/2. Original shape: a hexagon us-
ing your circle2 function. Transformed shapes are in mygray and mygold,
respectively. First marker is the first point, the second marker is the second
point. Plot all three shapes: the original and two transformed, on the same
figure.
(c) Rotation example with θ =?. Original shape: a pentagon. Notice that using
your circle2 function to create the pentagon makes the shape “off kilter”
or tipped. We want to orient the pentagon so the bottom side is perfectly
horizontal, so we need to rotate it by an appropriate angle θ . Figure out what
θ should equal and use this angle for your rotation example. Transformed
shape should be in myred. First marker is the first point, the second marker
is the second point.
(d) Two composition examples Original shape: a triangle using your
circle2. Transformed shapes are in myred and mygold, respectively. First
marker is the first point, the second marker is the second point. The first
transformation is a reflection about the y-axis (what is θ ?) followed by a
rotation with θ = π/4. The second transformation is the rotation and then
reflection. Plot all three shapes on the same figure.
(e) Two random transformations Original shape: the ellipse. Transformed
shapes are in mygray and mygold. First marker is the first point, the second
marker is the tenth point. The matrix for these random linear transformations
are 2 × 2 matrices with random integer entries from −5 to 5.
(f) Two random transformations Original shape: the square. Transformed
shapes are in mygray and mygold. First marker is the first point, the second
marker is the second point. The matrix for these random linear transforma-
tions are 2 × 2 matrices with random integer entries from −5 to 5.
3. Visualizing affine transformations For this problem we will be doing the fol-
lowing:
144 Programming Mathematics Using MATLAB®
• Save the affineData.mat file found on the text website to your folder/directory
and use the load('affineData') command to load the matrices and vectors
for the affine transformations (listed below).
• Draw the hexagon using your circle2 in black.
• Calculate the transformed hexagon using the affine transformations below (T1
for the first transformation, T2 for the second, etc.).
• Plot the transformed hexagons in mygreen, myred, and mygold, respectively.
• Use the command axis equal and define the axes to an appropriate view so
the hexagons do not touch the edge of the figure.
• Have a legend identifying the original, first transformation, etc.
• No axis labels are needed for these graphs.
• The title of the graph should be “Affine Transformations.”
Affine transformations Tk (x) = Mk x + vk , (k = 1, 2, 3) where
0 1 1.5 3 1 −1.25
M1 = , v1 = , M2 = , v2 = ,
3 1 0 0 1 −1.25
−3 0 −1
M3 = , v3 = .
2 3 1
ii. Load the variables found in fernIFS.mat that can be found on the text
website to have the matrices, vectors, and probabilities that are needed to
do the following
tasks.
0
iii. Let x = .
0
iv. If n is the only input, plot the point x as a point using “*” marker. Oth-
erwise, plot the point with the additional inputs using varargin.
v. Use the random number generator rand to select one of the affine trans-
formations Tk according to the given probabilities.
vi. Redefine x to be the new x = Tk (x) = Mk x + vk .
vii. Plot the new point x as you did with the original x.
viii. Repeat steps (vi) through (viii) so a total of n new points are plotted
(where should the hold on and hold off commands be? How many
times should your loop iterate?).
ix. The last command of the function should be storing toc into your output
variable to capture the time it took to generate and plot the fern fractal.
(b) For fern2, we will adjust the process of fern1 by vectorizing the code.
i. Use the command tic.
ii. Load the variables in fernIFS.mat found on the text website to have the
matrices, vectors, and probabilities that are needed to do the following
tasks.
0
iii. Let x = and set X = x.
0
iv. Use the random number generator rand to create a vector of n random
numbers to determine all of the affine transformations.
v. Repeat the following so a total of n new points are in the matrix X:
A. Select one of the affine transformations Tk according to the given
probabilities using the appropriate element from the vector of ran-
dom numbers created above.
B. Redefine x = Tk (x) = Mk x + vk . Concatenate X with the new x (add
another column to X that is the new x).
146 Programming Mathematics Using MATLAB®
vi. If n is the only input, plot the points in the matrix X as a point using
“*” marker. Otherwise, plot the points with the additional inputs using
varargin. (Note that the first row of X contains the x-coordinates, the
second row contains the y-coordinates.)
vii. The last command of the function should be storing toc into your output
variable to capture the time it took to generate and plot the fern fractal.
(c) For fern3, we will adjust the process of fern2 by preallocation.
i. Use the command tic.
ii. Load the variables in fernIFS.mat found on the text website to have the
matrices, vectors, and probabilities that are needed to do the following
tasks.
iii. Define x as a matrix with two rows and n + 1 columns of zeros.
iv. Use the random number generator rand to create a vector of n random
numbers to determine all of the affine transformations.
v. For columns 2 through n + 1 of x, use the appropriate element from
the vector of random numbers created above to select one of the affine
transformations Tk according to the given probabilities and let that column
of x equal Tk (previous column of x).
vi. If n is the only input, plot the points in the matrix x as a point using
“*” marker. Otherwise, plot the points with the additional inputs using
varargin. (Note that the first row of x contains the x-coordinates, the
second row contains the y-coordinates.)
vii. The last command of the function should be storing toc into your output
variable to capture the time it took to generate and plot the fern fractal.
5. Display the fern using fern1, fern2, and fern3 with n = 2000. Before each fern
command, use the command clf, and after each fern command, use the commands
axis equal and axis off. For each of the ferns, use the sprintf command to
create titles that say which fern function, the value of n, and how much time elapsed
to create the fern fractal.
6. Display the fern using fern1, fern2, and fern3 with n = 5000, and specify the
square marker, color mygreen, and have the marker size be smaller than the default.
Before each fern command, use the command clf, and after each fern command,
use the commands axis equal and axis off. For each of the ferns, use the
sprintf command to create titles that say which fern function, the value of n,
and how much time elapsed to create the fern fractal.
7. Display the fern using fern2 and fern3 with n = 50,000 and specify a marker
and a color of your choice (do not use the default color). Use other specifiers if
you want. Before each fern command, use the command clf, and after each fern
command, use the commands axis equal and axis off. For each of the ferns,
use the sprintf command to create titles that say which fern function, the value
of n, and how much time elapsed to create the fern fractal.
CHAPTER 9
This still does not show us how to understand the importance of using complex
numbers for multiplication rather than vectors. Representing complex numbers in a
different way shows us the meaning and use of multiplication.
Complex Numbers and Fractals 149
As we learned in Calculus II, there are two ways one can identify points on the
2D plane: Cartesian coordinates (x, y) and polar coordinates (r , θ ) using the conversion
formulas:
x = r cos θ,
y = r sin θ,
x + y2 = r 2 ,
2
y
= tan θ.
x
With this idea, using z = x + iy one has the polar representation of a complex
number:
z = x + iy = r cos θ + ir sin θ
where r is the length, norm, or magnitude of z (r = |z| = x2 + y2 ) and θ is the
argument of z (the angle of rotation from the positive real-axis to z).
Using trigonometry and polar representations, we can visualize what happens when
we multiply complex numbers. Using trigonometric identities, one can prove de
Moivre’s formula/theorem:
zn = r n cos(nθ ) + ir n sin(nθ ).
This means that when we take a complex number and raise it to a positive integer
power n, the result is a complex number in which the length is taken to that power n
and the argument is multiplied n times (thus rotated n times).
√
Consider the graph below. For the number z = 2 + 2i, we have r = |z| = 2 2, and
π π √
θ = . Thus z2 has length r 2 = 8, and argument 2θ = . Also, z3 has length r 3 = 8 8,
4 4
3π
and argument 3θ = (see Fig. 9.4).
4
If we let z = r cos θ + i sin θ and w = s cos ψ + is sin ψ , then using trigonometric iden-
tities we get
zw = rs cos(θ + ψ) + irs sin(θ + ψ).
Thus the lengths are multiplied and the arguments (angles of rotation) are
added.
150 Programming Mathematics Using MATLAB®
√
Consider
√
the complex numbers pictured in Fig. √ 9.5: z1 = 2 cos(π/4) + i2 sin(π/4) =
2 + i 2 and z2 = 6 cos(π/3) + i6 sin(π/3) = 3 + (3 3)i. If we multiply them using the
polar representation, we get
√ √ √ √
z3 =12 cos(7π/12) + i12 sin(7π/12). = (3 3 − 3 6) + i(3 6 + 3 2) ≈ −3.1058
+ 11.5911i.
x1=[2;3]; x2=[6;5];
x=[x1 x2];
plot(x(1,:),x(2,:),'*')
a=2+3i; b=6+5i;
plot([a b],'*')
a=2+3i; b=6+5i;
plot([a b])
A word of caution: if you have a purely real number and want it plotted as a complex
number, then you either have to have it within a vector of other complex numbers or
plot the real and imaginary part separately. For example, x=[2,i]; plot(x,'∗') will
plot the 2 correctly, but if you have x=2; instead, or even x=2+0∗i, you will not get the
desired results.
Figure 9.7 Scaling and shifting. (A) Shifting the line segment, (B) Scaling a line segment.
Figure 9.8 Scaling and shifting again. (A) Scaled vector starting at a, (B) Scaled vector starting at b.
Complex Numbers and Fractals 153
Figure 9.11 A few turns of the Chaos Game (with turns marked for demonstration).
How one gets the line segments for the Gosper Curve is by taking the points (com-
plex numbers) a and b and calculating the points x1 and x2 and connecting the points
a, x1 , x2 , and b. The length of each subsequent line segment is the length of b√−7a . The
√
point x1 is rotated from the segment b − a by an angle of θ1 = tan−1 53 . The point x2
is rotated from the segment b − a by an angle of θ2 = θ1 − π (see Fig. 9.17). Then the
Gosper Curve is repeated around a hexagon Figs. 9.18 and 9.19).
The following theorem is provided without proof and can be found in any calculus
book.
Complex Numbers and Fractals 157
9.5. Exercises
1. Chaos Game We will simulate the Chaos Game and use complex numbers. Our
seed will be a complex number generated by the rand command for the real and
imaginary values of the seed. You will create a function file called chaosGame that
has one or more inputs. The first input is a positive integer n that will determine
the number of “rolls of the die” there will be in the Chaos Game, or more inputs.
The additional inputs, which are optional, will be marker specifications for drawing
the points. The output of the function will be the time elapsed (generated by the
commands tic and toc) to play the game. Your function file will do the following.
(i) Capture the start time with tic.
(ii) Perform the error check on the function input n and use the error com-
mand with appropriate message.
(iii) Generate the three vertices of the equilateral triangle as cos θ + i sin θ for θ
from π/2 to 2π + π/2, with an increment of 2π/3. The triangle must be so
the bottom base is horizontal. Draw the triangle in a solid black line.
(iv) Store the default colors using the commands
colors = lines(8); colors(8,:)=[0,0,0];
(v) Draw the vertices using the “o” marker and color them using three of the
default colors stored in colors. To make them more visible, specify the
MarkerFaceColor and MarkerEdgeColor to be the appropriate color. You
may want the MarkerSize to be larger than the default. (Hint: a for loop
may be useful!)
(vi) Preallocate a vector to the appropriate size to contain the “seed” and the n
points generated by the n rolls of the die.
(vii) Generate the seed to be in the first element of this vector by using the rand
command. This seed should be a complex number. (How would we get a
random complex number using the rand command?) Note that this seed
point need not be inside the triangle.
(viii) Now play the Chaos game for n turns: Use randi to simulate a roll of
a standard die. The next element of your vector will be the point that is
halfway between the current element and the vertex chosen by the “roll of
the die”. Note that you must make it so each vertex has an equal chance of
being chosen by a roll of the die.
(ix) After all of the turns are completed (thus the vector has been filled with the
complex numbers obtained from the turns of the Chaos Game), either plot
the points in the vector as black periods ('k.') or use the varargin to plot
the points.
(x) The output of the function is the time elapsed as determined by toc.
Complex Numbers and Fractals 159
(a) Play the game for n = 10 with no other input. Use axis off and axis
equal commands. Put a meaningful title on the figure that has the number
of iterations and time elapsed.
(b) Do the same as above but for n = 200, have the marker be “*” and set the
MarkerSize to 3.
(c) Do the same as above but for n = 30,000 and specifying a black “o” with
MarkerSize of 1.
2. Chaos Game 2 We will simulate a modified version of the Chaos game and use
complex numbers. We will use a square instead of a triangle and have eight “ver-
tices” that are the corners and midpoints of the sides. Our seed will be a complex
number generated by the rand command for the real and imaginary values of the
seed. You will create a function file called chaosGameSquare.m that has one or
more inputs. The first input is a positive integer n that will determine the number
of “rolls of the die” there will be in the Chaos Game. The additional inputs, which
are optional, will be marker specifications for drawing the points. The output of
the function will be the time elapsed (generated by the commands tic and toc) to
play the game. Your function file will do the following.
(i) Capture the start time with tic.
(ii) Perform the error check on the function input n and use the error com-
mand with appropriate message.
(iii) Store the vertices of the square in a vector: 1, 1 + i, i, −1 + i, −1, −1 − i, −i,
1 − i (you may want to add extra 1 at the end to make it easier to draw...)
Draw the square in a solid black line.
(iv) Store the default colors using the commands
colors = lines(8); colors(8,:)=[0,0,0];
(v) Draw the vertices using the “o” marker and color them using the de-
fault colors stored in colors. To make them more visible, specify the
MarkerFaceColor and MarkerEdgeColor to be the appropriate color. You
may want the MarkerSize to be larger than the default. (Hint: a for loop
may be useful!)
(vi) Preallocate a vector to the appropriate size to contain the “seed” and the n
points generated by the game.
(vii) Generate the seed to be in the first element of this vector by using the rand
command. This seed should be a complex number. (How would we get a
random complex number using the rand command?)
(viii) Generate n rolls of an eight-sided die in a vector rolls.
(ix) Now play the Chaos Game for n turns: Using the rolls vector to determine
the chosen vertex, the next element of your vector of points will be gone
from the previous element to 1/3 of the distance between the previous
element and the chosen vertex.
160 Programming Mathematics Using MATLAB®
(x) After all of the turns are completed (thus the vector has been filled with the
complex numbers obtained from the turns of the Chaos Game), either plot
the points in the vector as periods ('.') or use the varargin to plot the
points.
(xi) The output of the function is the time elapsed as determined by toc.
Once the function is created, play the game as follows.
(a) Play the game for n = 50 with no other inputs. Use axis off and axis
equal commands. Put a meaningful title on the figure that has the number
of iterations and time elapsed (using sprintf).
(b) Do the same as above but for n = 1000.
(c) Do the same as above but for n = 50,000 and specifying a black period with
MarkerSize of 2.
3. Chaos Game 3 We will simulate a modified version of the Chaos game and use
complex numbers. We will use a pentagon instead of a triangle. The function will
be chaosGamePent. We will do as in Exercise 2 except for the initial shape and
vertices, the die will be a five-sided die, and in step 2ix, the next element will be the
point that is 3/8 the distance between the current element and the vertex chosen
by the “roll of the die.” Note that the definition of the pentagon and its vertices
should be such that it lies flat on the bottom of the figure. This can be done with
the equation sin θ + i cos θ for θ = k(2π/5) for k = 1, 2, . . . , 5.
(a) Play the game for n = 100 with no other inputs. Use axis off and axis
equal commands. Put a meaningful title on the figure that has the number
of iterations and time elapsed (using sprintf).
(b) Do the same as above but for n = 1000.
(c) Do the same as above but for n = 30,000 and specifying a period with Mark-
erSize of 1.
4. Chaos Game 4 We will simulate a modified version of the Chaos game and use
complex numbers. We will use a hexagon instead of a triangle. The function will be
chaosGameHex. We will do as in Exercise 2 except for the initial shape and vertices,
the die will be a standard die, and in step 2ix, the next element will be the point
that is 1/3 the distance between the current element and the vertex chosen by the
“roll of the die.” Note that the definition of the hexagon and its vertices should be
such that it lies flat on the bottom of the figure. This can be done with the equation
cos θ + i sin θ for θ = k(π/3) for k = 1, 2, . . . , 6.
(a) Play the game for n = 100 with no other inputs. Use axis off and axis
equal commands. Put a meaningful title on the figure that has the number
of iterations and time elapsed (using sprintf).
(b) Do the same as above but for n = 1000.
(c) Do the same as above but for n = 30,000 and specifying a period with Mark-
erSize of 1.
Complex Numbers and Fractals 161
5. Koch Snowflake We will create a function kochSnowflake that will have a nested
function kochpoints that will draw the Koch Snowflake fractal at the nth iter-
ation. The input for kochSnowflake will be a nonnegative integer n (return an
appropriate error message if n is not a nonnegative integer). The output will be the
time elapsed using the tic and toc commands.
Pseudocode for function kochSnowflake
• Capture the start time.
• Check that n is a nonnegative integer; if not, give appropriate error message
using the error command.
• Create a vector v of vertices of the equilateral triangle; calculated by cos(kθ ) +
i sin(kθ ) for k = 1, . . . 4 (so they connect) for the appropriate θ or by using your
mycircle2 function. The triangle must be so the bottom base is horizontal.
• If n = 0, plot the triangle. Calculate the time elapsed and use the return com-
mand.
• Initialize a vector S to be the first vertex of the triangle (stored in v) and create
a loop that will use the nested function kochpoints on the last element of S,
the next vertex of the triangle (stored in v) for n iterations. If we looped through
using the nested function kochpoints on each of the vertices of the hexagon,
there would be repeated points. Thus for each of the three sides of the triangle,
we replace S with S minus the last element and concatenate it with the points
from the nested function kochpoints using the last element of S and the next
vertex (stored in v) using the given n.
• Plot the sets of vertices S.
• Capture the time elapsed for the output of the function.
Pseudocode for nested function kochpoints: has inputs a, b, and n and output
vector V .
• Define the output V to have the elements a and b.
• Repeat the following n times:
– Define an empty vector B.
– From 1 to [(number of elements in V ) − 1]
∗ let a = the current element of V and b = the next element of V .
∗ Calculate x1 to be the point that is 1/3 of the way from a towards b.
∗ Calculate x2 to be the point that is the midpoint between a and b MINUS
√
3/2i(b − a)/3.
∗ Calculate x3 to be the point 2/3 of the way from a towards b.
(OR USE ANY DERIVATIONS FOR x1, x2, and x3 we did in class or
you come up with on your own.) As long as it gives the proper picture, it
is fine. Keep in mind that your derivation should have as few calculations
as possible in order to speed up the code. To speed up the code even
more, if you are using the same calculations in several of these formulas,
162 Programming Mathematics Using MATLAB®
perform the calculation first, storing it as some variable, and then use the
variable within the calculations.
∗ Concatenate B with the elements a, x1, x2, and x3.
– Now we redefine V . The new V will be B concatenated with the last ele-
ment of the current V .
Once the function is created, we will visualize the snowflake as follows.
(a) Use subplot to have two rows, two columns of the snowflake plotted for
n = 0, 1, 2, 3 (capture the time elapsed for each). Hint: it may be easiest to
have a for loop for this.
• For each snowflake/subplot, capture the time elapsed.
• For each snowflake/subplot, use the axis equal and axis off com-
mands.
• For each snowflake/subplot, create a title with “n = , y s” where y is
the time elapsed to create that subplot. For example, you may see a title
such as “n = 3, 0.3456 s” because the third iteration of the snowflake
took 0.3456 s (made up numbers).
(b) Create another plot (NOT A SUBPLOT) that for n = 5 with a similar title
as above that gives the number of iterations and time elapses, using axis
equal and axis off.
(c) Calculations For the snowflake, calculate the following, where iteration
n = 0 is the triangle. Show all work on paper (turned in).
i. Create a chart that has for each iteration n the number of sides/line seg-
ments, the number of new triangles that replaces part of the line segment
at that iteration (this √will be 0 for n = 0), the length of the side of the
triangle at this stage ( 3 for n = 0), and the area of the triangle. Do this
for n = 0, n = 1, n = 2, n = 3, and n = k for some k ≥ 1.
ii. The area An enclosed by the snowflake at iteration n. Also find the limit
A = lim An , if it exists.
n→∞
iii. The perimeter Pn of the snowflake at iteration n. Also find the limit
P = lim Pn , if it exists.
n→∞
6. Fractal Snowflake We will create a function snowflake that will have a nested
function snowflakepoints that will draw the Snowflake fractal at the nth it-
eration. The input for snowflake will be a nonnegative integer n (return an
appropriate error message if n is not a nonnegative integer). Any additional in-
puts will be plot specifications. The output will be the time elapsed using the tic
and toc commands.
Pseudocode for function snowflake:
• Capture the start time.
• Check that n is a nonnegative integer; if not, give appropriate error message
using the error command.
Complex Numbers and Fractals 163
(a) Use subplot to have 2 rows, 2 columns of the snowflake plotted for n =
0, 1, 2, 3 (capture the time elapsed for each). Hint: it may be easiest to have
a for loop for this.
• For each snowflake/subplot, capture the time elapsed.
• For each snowflake/subplot, use the axis equal and axis off com-
mands.
• For each snowflake/subplot, create a title with “n = , y s” where y is
the time elapsed to create that subplot. For example, you may see a title
such as “n = 3, 0.3456 s” because the third iteration of the snowflake
took 0.3456 seconds (made up numbers).
(b) Create another plot (NOT A SUBPLOT) that for n = 5 and optional color
“Deep Sky Blue” that has rgb(0, 191, 255) (remember how you need to
convert to a vector for MATLAB to recognize the RGB color). Have a
similar title as above that gives the number of iterations and time elapses,
and also using axis equal and axis off. Set the background color to
white using set(gcf,'Color','w').
(c) EXTRA CREDIT: figure out how to make an animated gif of the iterations
looping from n = 0 to n = 5 (no title).
7. Gosper Island We will create a function gosper that will have a nested function
gosperpoints that will draw the Gosper Island fractal at the nth iteration. The in-
put for gosper will be a nonnegative integer n (return an appropriate error message
if n is not a nonnegative integer). The output will be the time elapsed using the tic
and toc commands.
Pseudocode for gosper.
• Capture start time.
• Check that n is a nonnegative integer; if not, give appropriate error message.
• Create a vector v of vertices of a hexagon; calculated by cos(kθ ) + i sin(kθ ) for
k = 1, . . . 7 (so they connect) for the appropriate θ or by using your mycircle2
function.
• Initialize a vector G to be an empty vector.
• For each of the six sides of the hexagon (sides between points v(k) and v(k + 1),
use the nested function gosperpointsLO, to get the new vertices.
• Plot the sets of vertices G.
• Capture the time elapsed.
Pseudocode for gosperpoints
√
: has inputs a, b, and n and output V .
−1
• Let θ1 = tan ( 3/5), and θ2 = θ1 − π .
• Calculate the two rotations r1 = cos(θ1 ) + i sin(θ1 ), and r2 = cos(θ2 ) + i sin(θ2 ).
• Define the output V to have the elements a and b.
• Repeat the following n times:
– Define an empty vector B;
Complex Numbers and Fractals 165
The proof of this is not given here. Notice that many times (and indeed, even in
lecture), this is split up into two theorems; the first with the statement giving the suffi-
cient conditions for an alternating series to converge, and the second has the statement
about the remainder. For brevity’s sake it is combined here into one theorem.
Example 10.1.2. The alternating harmonic series converges by the alternating series
estimation theorem, as bn = 1n is a decreasing sequence that converges to 0. In addition,
if we looked at
1 1 1 1 47
s5 = 1 − + − + = = 0.783̄,
2 3 4 5 60
then |R5 | ≤ b6 = 16 . Thus the actual sum s of the series is somewhere in the interval
47 1 37 57
± , or between and , or between 0.616̄ and 0.95.
60 6 60 60
Recall that a series an is absolutely convergent if |an | converges. An impor-
tant theorem tells us that any absolutely convergent series converges, but not necessarily
vice versa. This gives us the term conditionally convergent; a series is conditionally
convergent if an converges but |an | diverges.
Two useful tests for convergence are the ratio and root tests. There are, of course,
others but for now we will remind you of these two without proof.
Theorem 10.1.2 (Ratio test). Consider the series an and let
an+1
lim = L.
n→∞ a n
(a) If L < 1, the series an is absolutely convergent.
(b) If L > 1 (including L = ∞), the series an diverges.
(c) If L = 1, the ratio test is not applicable.
Theorem 10.1.3 (Root test). Consider the series an and let
lim n
|an | = L .
n→∞
(a) If L < 1, the series an is absolutely convergent.
(b) If L > 1 (including L = ∞), the series an diverges.
(c) If L = 1, the ratio test is not applicable.
Series and Taylor Polynomials 169
∞
(−1)n
Example 10.1.4. Consider the series .
n=0
n!
We have
an+1 1
lim = lim (n+1)!
n→∞ a n n→∞ 1
n!
n!
= lim
n→∞ (n + 1)!
1
= lim = 0.
n→∞ n+1
Since this limit equals zero, which is certainly less than one, the series is absolutely
convergent by the ratio test.
All of the above are useful, but they are really used in the context of power series, and
in particular, Taylor series.
The main questions about power series are: “For what values of x does the series
converge?” and “What does the series equal?” Knowing these answers allow us to see
why we care about power series. In other words, when does the infinite sum make
sense, and given a value of x, when does it equal some real number, even if it is difficult
to find that exact real number? Notice that every power series converges at x = x0 . But
if that were the only case, then power series would not be useful at all. So we want
power series that converge for additional values of x.
The goal is to REPRESENT A FUNCTION, ESPECIALLY A COMPLICATED
FUNCTION, AS A POWER SERIES. This is tremendously useful for approximations
and calculations and many other results beyond the scope of this course.
170 Programming Mathematics Using MATLAB®
∞
Theorem 10.2.1. Consider the power series an (x − x0 )n .
n=0
(a) If the power series converges at c = x0 , then it converges for all
x such that |x − x0 | < |c − x0 |.
(b) If the power series diverges at d ∈ R, it diverges for all x such
that |x − x0 | > |d − x0 |.
Proof. Suppose there exists c = x0 such that the power series converges. We will show
that, for every x such that |x − x0 | < |c − x0 |, the series converges.
Let x ∈ R such that |x − x0 | ≤ r < |c − x0 |. We know that ∞ 0 an (c − x0 ) is convergent,
n
so
lim an (c − x0 )n = 0.
n→∞
The above theorem is useful, but is mostly used to prove the following theorem.
∞
Theorem 10.2.2. For a given power series an (x − x0 )n , there are
n=0
only three possibilities:
(a) The series converges only when x = x0 .
(b) The series converges for all x ∈ R.
(c) There exist R > 0 such that the series converges if |x − a| < R
and diverges if |x − a| > R.
Proof. Consider Theorem 10.2.1. If no such c = x0 exists, we have case 1 of the theorem.
If no such d exists, we have case 2 of the theorem.
Now suppose we have both a point c = x0 where the series converges and a point d
where the series diverges. Let C = |c − x0 | and D = |d − x0 | and consider the intervals
IC = (x0 − C , x0 + C ) and ID = [x0 − D, x0 + D]. (Draw a picture!)
Series and Taylor Polynomials 171
Let S = {x ∈ R | series converges}. This set is non-empty since we have all x ∈ S for
all x ∈ IC by Theorem 10.2.1. By the same theorem, x ∈/ S for all x ∈/ ID . Thus x0 + D is
an upper bound for S since for all x > x0 + D, the series diverges so is not in S. By the
completeness axiom of real numbers, S has a “least upper bound”, which we will call
R. We know that R > 0. This tells us if |x − x0 | < R, x ∈ S, and if |x − x0 | > R, x ∈/ S,
and the result is proven.
In the third case, what happens when |x − a| = R depends on the series and you
have to check. In other words, some series converge at the endpoints, others diverge,
and others converge at one endpoint and diverge at the other.
The number R is called the radius of convergence and in the first case of Theo-
rem 10.2.2, we say R = 0. In the second case of Theorem 10.2.2 we say R = ∞. In the
third case, you have four possibilities for the interval of convergence:
This theorem is important because it tells us that a power series will never only
converge at a few points, or only on the integers, etc.
(−1)n xn
Example 10.2.1. Consider the power series . We see that
n!
|x|n+1
an+1
lim = lim (n+1)!
n→∞ a n n→∞ |x|n
n!
n!|x|
= lim
n→∞ (n + 1)!
|x|
= lim = 0.
n→∞ n + 1
Thus the series is absolutely convergent for any x ∈ R by the ratio test. Thus the radius
of convergence is R = ∞ and the interval of convergence is I = (−∞, ∞).
Example 10.2.2. Compare the radii and intervals of convergence of the following
series. The work is shown for one of the series. Can you see how to get the answers for
the others?
∞
(a) (x − 7)n . R = 1, I = (6, 8).
n=0
∞
(x − 7)n
(b) , R = 1, I = [6, 8).
n=1
n
|x−7|n+1
an+1
lim = lim n+1
n→∞ a n n→∞ |x−7|n
n
172 Programming Mathematics Using MATLAB®
n|x − 7|
= lim = |x − 7|.
n→∞ n + 1
By the ratio test, the power series converges when |x − 7| < 1, and diverges when
|x − 7| > 1 and so R = 1. But when |x − 7| = 1, i.e., when x = 6 and x = 8, the
ratio test is not applicable so we look at each of these cases separately. When x =
(x − 7)n (−1)n
6, the power series = which is the alternating harmonic
n n
series, which converges. When x = 8, the power series is the harmonic series,
which diverges. Thus I = [6, 8).
∞
(x − 7)n
(c) , R = 1, I = [6, 8].
n=1
n2
∞
(d) n!(x − 7)n , R = 0, I = {7}.
n=0
∞
(x − 7)n
(e) , R = ∞, I = (−∞, ∞).
n=0
n!
The next theorem is very useful because it allows us to get series for more functions,
and possibly use Taylor polynomials (see Section 10.3 below) for approximating these
functions.
Theorem 10.2.3. If f (x) is analytic (can be represented as
a power
series) with f (x) = an (x − a)n and R > 0, then f (x) and f (x) dx
can also be represented as a power series with radius of convergence
also R. In addition, for all x ∈ (a − R, a + R),
∞
f (x) = nan (x − a)n−1 = a1 + 2a2 (x − a) + 3a3 (x − a)2 + · · ·
n=1
and
∞
(x − a)n+1 (x − a)2
f (x) dx = C + an = C + a0 (x − a) + a1 + ···
n=0
n+1 2
and
an (x − a) dx =
n
an (x − a)n dx.
IMPORTANT: the theorem tells us the radius of convergence stays the same, yet the
actual interval of convergence may change as demonstrated in the following example.
∞
(x − 7)n
Example 10.2.3. Consider the series from Example 10.2.2 above. We
n=1
n
∞
(x − 7)n
got R = 1, I = [6, 8). Let f (x) = . Theorem 10.2.3 tells us that, for all x ∈
n=1
n
(6, 8), the derivative exists and is
∞
∞
∞
n(x − 7)n−1
f (x) = = (x − 7)n−1 = (x − 7)n .
n=1
n n=1 n=0
Thus R = 1 for the series for f (x). Upon further investigation, we see that the interval
of convergence for this series for f (x) is now (6, 8), which is different from the interval
of convergence for f (x).
Taylor series are useful in their own right, but are most useful when looking at the
partial sums of the series, known as Taylor polynomials.
174 Programming Mathematics Using MATLAB®
since f (n) (0) = 1 for all n. Fig. 10.1 above shows how Taylor polynomials are decent
approximations for the exponential function near x = 0, and the higher degree of Taylor
polynomial used, the better this approximation becomes, even for values further away
from x = 0.
f (n) (a)
an = , n = 0, 1, 2, . . .
n!
f (n+1) (c )
Rn (x) = (x − a)n+1
(n + 1)!
Note: this formula for the remainder is known as Lagrange’s form of the remainder.
There are other forms of the remainder. Here are two other famous forms:
f (n+1) (c )
Rn (x) = (x − c )n (x − a) Cauchy’s form,
n
!
1 x (n+1)
Rn (x) = f (t)(x − t)n dt Integral form.
n! a
176 Programming Mathematics Using MATLAB®
Here is another way one can estimate the error when using Taylor polynomials to
estimate the function represented by a Taylor series:
Theorem 10.3.4 (Taylor’s inequality). Suppose f (x) is represented as
a power series centered at a with R > 0. If |f (n+1) (x)| ≤ M for all x
with |x − a| ≤ δ , then the remainder Rn (x) of the Taylor series satisfies
M
|Rn (x)| ≤ |x − a|n+1 for |x − a| ≤ δ.
(n + 1)!
If you read the above theorems carefully, you may notice that it is NOT quite the
case that “f is analytic iff f is infinitely differentiable. Here is a counterexample:
Example 10.3.2. Center the series at a = 0 for f (x):
e−1/x x > 0,
f (x) =
0 x ≤ 0.
It can be shown (can you show it?) that, while f is infinitely differentiable, even at 0,
there is no power series (with R > 0) centered at 0 (look at Lagrange’s form of the
remainder for x > 0 close to 0).
The good news is that many functions that we are familiar with CAN be represented
by a Taylor or Maclaurin series.
Common Maclaurin series (look up others in your calculus book):
∞
xn
ex = R = ∞,
n=0
n!
∞
(−1)n x2n
cos x = R = ∞,
n=0
(2n)!
∞
(−1)n x2n+1
sin x = R = ∞,
n=0
(2n + 1)!
(−1)n x2n+1
tan−1 x = R = 1,
2n + 1
∞
1
= xn R = 1.
1−x n=0
The following examples show the usefulness of Theorem 10.2.3 when applied to
Maclaurin and Taylor series.
Example 10.3.4. What is a Maclaurin series for ln(1 − x) centered at 0? What is its
radius of convergence?
∞
1
Example 10.3.5. Consider the geometric series xn =, for |x| < 1.
n=0
1 − x
1
(a) Use the geometric series above to find a series for . What is the radius of
1 + x2
convergence?
(b) Use Theorem 10.2.3 to find a series for tan−1 x. What is the radius of conver-
gence? Interval of convergence?
∞
(−1)k π
(c) Prove the Leibniz series identity: = .
k=0
2k + 1 4
Example 10.3.6. Using the Maclaurin series for ln(1 + x), show that
∞
(−1)k+1
ln 2 = .
k=1
k
10.4. Exercises
1. Create a function isnnInt that will have one input, n, and the output will be a
logical true/false as to whether n is a nonnegative integer (but not necessarily of
data type integer; data type double is still allowed). Note that no error messages
are displayed with this function; it returns either true or false.
2. This problem looks at the Leibniz series
∞
π (−1)k
= .
4 2k + 1
k=0
The nth partial sum of the series can be used to estimate π/4 and thus other values
with π (this is a crude estimation; other/better estimations are a topic for another
178 Programming Mathematics Using MATLAB®
course). Notice that it is an alternating series. Your leibniz function will have the
following features.
• The function has one input, n, which should be a nonnegative integer.
Use your function isnnInt to check it; if not, an appropriate error message is
displayed using the error command.
• The function will have two outputs. The first output is the nth partial sum of
the Leibniz series:
n
(−1)k π
≈ .
(2k + 1) 4
k=0
A loop can be used for this calculation but it may be fastest if you use vector-
ized code instead. The second output will be the estimated error of this partial
sum using the alternating series estimation theorem.
3. The next function nleibniz2 will not calculate partial sums, but instead tell you
what n should equal used in order to use the leibniz function to approximate π/4
to a certain degree of accuracy (“tolerance level”).
• The nleibniz2 function has one input: a “tolerance level” ε for using the partial
sum.
• Your function should check that ε > 0; if not, an appropriate error message is
displayed using the error command.
• The function figures out the minimum value of n (obtained from the alter-
nating series estimation theorem) for the nth partial sum to have an error less
than or equal to ε. The output of the function is this value n.
4. Use your function leibniz to estimate π and its error. (Careful! You need to
adjust your answers from the answer you get from your function for this!). Note
that even though MATLAB® has an accurate estimation of π , do not use this
to estimate the error. Use n = 3, n = 9, n = 99, and n = 9999. Use the fprintf
command to make your answers appear like below, with the same number of
decimal places shown (it may be more convenient to have more than one fprintf
command). Note that the numbers below are made up for display purposes.
Using the partial sum of the Leibniz series:
n Estimate Error estimate Between
3 3.123456789 1.123456789 2.00000000 and 4.24691358
9 3.143456789 0.123456789 3.02000000 and 3.26691358
99 3.141556789 0.012345678 3.12921111 and 3.15390247
9999 3.141596789 0.001234567 3.14036222 and 3.14283136
5. Using nleibniz2, what value of n should be used to get the estimate of π accurate
to six decimal places? Careful! What would the error tolerance need to equal to
be within that many decimal places, and how do you adjust between error for π/4
and error for π ?
Series and Taylor Polynomials 179
Create a function called mycos.m that calculates the nth-degree Taylor polynomial
for f (x) = cos(x) using the above Maclaurin series for cos(x). The function should
have two inputs; x and n. Make sure that n is a nonnegative integer using your
180 Programming Mathematics Using MATLAB®
function isnnInt; if not, an appropriate error message is displayed using the error
command. The calculations should be such that x can be a number, vector, or
matrix. The input n is the highest degree term that will appear in the poly-
nomial. Thus if n = 8, the degree of the polynomial will be no bigger than 8.
Notice that if we enter n = 9, we should get the same as n = 8. Use the warning
command if an odd value of n is entered. Careful: if we want n = 8, what should k
equal for the last term in the sum? If we input n = 9, what should happen? Using
floor, ceil, or fix may be useful here. The output of the function will be the
calculated value of the Taylor polynomial Tn (x).
Plot the Taylor polynomials for x ∈ [−10, 10] for n = 4, n = j, n = k, and n = 24
using the above function mycos along with y = cos(x) on the same figure with the
following specifications.
• The values of j and k will be random integers between 6 and 12 determined
using the randi command. Use a while loop to make sure k = j.
• Have y = cos(x) dotted and in black, and have the others in different colors
and/or shapes (dotted, dashed, etc.). Use your own judgment on LineWidth,
etc. to make the graphs clear.
• Have an appropriate legend and title. (sprintf may be useful to put the values
of n in the legend!)
• The vertical axis should only be between −2 and 2.
10. This problem is looking at Taylor/Maclaurin series and Taylor polynomials for
f (x) = tan−1 (x).
∞
∞
(−1)(k−1) x2k−1 or (−1)k x2k+1
tan−1 (x) = = , x ∈ [−1, 1].
k=1
2k − 1 k=0
2k + 1
Create a function called myatan.m that calculates the nth-degree Taylor polynomial
for f (x) = tan−1 (x) using the above Maclaurin series for tan−1 (x). The function
should have two inputs; x and n. Make sure that n is a nonnegative integer using
your function isnnInt; if not, an appropriate error message is displayed using the
error command). The calculations should be such that x can be a number, vector,
or matrix. The input n is the highest degree term that will appear in the
polynomial. Thus if n = 8, the degree of the polynomial will be no bigger than
8. Notice that if we enter n = 8, we should get the same as n = 7. Use the warning
command if an odd value of n is entered. Careful: if we want n = 7, what should k
equal for the last term in the sum? If we input n = 8, what should happen? Using
floor, ceil, or fix may be useful here. The output of the function will be the
calculated value of the Taylor polynomial Tn (x).
Plot the Taylor polynomials for x ∈ [−1.5, 1.5] for n = 3, 5, 13, and 52 along with
y = tan−1 (x) (atan) using the above function myatan on the same figure with the
following specifications.
Series and Taylor Polynomials 181
• Have y = tan−1 (x) dotted and in black, and have the others in different colors
and/or shapes (dotted, dashed, etc.). Use your own judgment on LineWidth,
etc. to make the graphs clear.
• Have an appropriate legend and title. (sprintf may be useful to put the values
of n in the legend!)
• The vertical axis should only be between −2 and 2.
11. Taylor series and polynomials for g(x) = tan−1 (x3 ).
(a) Using the Maclaurin series for tan−1 (x), find the Maclaurin series for
tan−1 (x3 ) and its radius of convergence, showing any work needed on paper.
State the formula along with its radius of convergence.
(b) Integrate the series you get in part (a) for a > 0 to get a series for the fol-
lowing integral:
a
a
g(x) dx = tan−1 (x3 ) dx,
0 0
also find the radius of convergence for the series for this integral, showing
all work on paper. State the formula for the series along with its the radius
of convergence.
(c) Create a function called atanint.m that calculates the nth-degree Taylor
polynomial for the series in part (b) for a given a and a given n. The func-
tion should check that a > 0, and that n is a nonnegative integer (use your
function isnnInt); if not, appropriate error messages would be displayed us-
ing the error command. Just as in myatan above, the input n should be
the highest degree that will appear in the partial sum (Taylor polynomial).
Notice that the series is an alternating series. Using the alternating series
estimation theorem, figure out what the estimated error would be for the
partial sum with input n, and take that as the second output. The second
output will be given whether or not it is asked for (such as the MATLAB
command/function size).
(d) Use properties of integrals, the fact that g(x) is either an even or odd func-
tion, and your function atanint if necessary to estimate the following (use
format long for these answers). Show all work on paper.
1/4
i. tan−1 (x3 ) dx (use n = 5 and n = 20),
0 1/4
ii. tan−1 (x3 ) dx (use n = 5 and n = 20),
−31//44
iii. tan−1 (x3 ) dx (use n = 5 and n = 20).
−1/4
Make sure your answers are clearly labeled.
CHAPTER 11
Numerical Integration
11.1. Approximating integrals/numerical integration
Our goal is to discuss basic ways to approximate the integral
b
f (x) dx.
a
The idea is that we view the integral as area “under the curve” (between the curve
and the x-axis, with negative area if the curve is below the x-axis). We approximate
the actual area (integral) by approximating the area with areas of regions that are easier
to calculate. The key for any of numerical integration techniques is to subdivide the
interval [a, b] into n subintervals. In this document we are making our lives easier by
dividing the interval into n subintervals of equal width:
b−a
x = .
n
Fancier methods would use different width subintervals depending on how the function
behaves on the domain, etc. Then n regions are formed based on the subdivisions and
the values of f (x), and the areas of these regions are calculated and totaled. The idea is
that, as n → ∞ or, equivalently, as the width x → 0, these approximations approach
b
the value of f (x) dx (see Fig. 11.1).
a
The subdivision of the interval [a, b] is such that a = x0 and b = xn to get
xk = a + kx, k = 0, 1, . . . n.
For the kth subinterval [x , x ], we choose a sample point x∗k ∈ [xk−1 , xk ]. The height
∗ k−1 k
of the kth rectangle is f xk . Thus the general form of using rectangles for approximating
b
a f (x) dx is
n
b ∗
f (x) dx ≈ f xk x.
a k=1
The three most common methods using rectangles are by using the left endpoint,
right endpoint, or midpoint of the subinterval to choose x∗k , and thus the height of the
rectangle (see Fig. 11.2 above).
Numerical Integration 185
We will not prove these error bounds in these notes; that is for a different course.
Notice that the error bounds get smaller faster for the midpoint rule than the trapezoidal
rule (which may seem counterintuitive).
A1 x2 + B1 x + C1 ,
one needs three points on the quadratic. Having these pairs of subintervals allows for
three data points at each approximation. Let us investigate the first estimating quadratic;
we want to estimate the area under the curve y = f (x) from x0 to x2 . We have three
data points: (x0 , f (x0 )), (x1 , f (x1 )), and (x2 , f (x2 )). For ease of notation, let us have
y0 = f (x0 ), etc.
Numerical Integration 187
In order to make finding the quadratic A1 x2 + B1 x + C1 easier, let us shift the x’s to
be from −h to h. So x0 → −h, x1 → 0, and x2 → h, with h = x (see Fig. 11.6).
Notice that the area under the curve does not change and we now have the data
points (−h, y0 ), (0, y1 ), and (h, y2 ) to figure out the approximating quadratic and/or
approximating area.
To figure out A1 x2 + B1 x + C1 :
x = 0 =⇒ C1 = y1 , (11.1)
x = −h =⇒ A1 h2 − B1 h + C1 = y0 , (11.2)
x = h =⇒ A1 h2 + B1 h + C1 = y2 . (11.3)
Thus
h
h
A1 x2 + B1 x + C1 dx = y0 + 4y1 + y2 .
−h 3
Now if we shift the x back, the area under the curve remains the same and we get
x2
h
A1 x2 + B1 x + C1 dx = y0 + 4y1 + y2 .
x0 3
Likewise
x4
h
A2 x2 + B2 x + C2 dx = y2 + 4y3 + y4 .
x2 3
Thus the general formula for the Simpson rule is
b
h
f (x) dx ≈ y0 + 4y1 + 2y2 + 4y3 + 2y4 + · · · + 2yn−2 + 4yn−1 + yn .
a 3
11.5. Exercises
Note that all ERROR CHECKS within your functions should use the error command
and display a meaningful error message.
1. Create a function RSum that takes as input a function fstring, a, b, n, sumType,
and color. The commands syms, str2sym, subs, and double may be useful or
necessary. The switch selection statement may also come in handy for this assign-
ment.
• The input fstring will be a string for the function f (x) that we want to in-
tegrate numerically. The string is in single quotes using standard MATLAB®
notation WITHOUT component-wise calculations. No error checking will be
done on this.
• The inputs a and b are the lower and upper bounds, respectively for the integra-
tion. An error check will check that a < b; if not, an appropriate error message
will be displayed.
• The input n will be the number of rectangles/subintervals that will be made for
the numerical integration (Riemann Sum). An error check will check that n is
a positive integer; if not, an appropriate error message will be displayed.
• The input sumType will determine which type of Riemann sum will be calcu-
lated and plotted. It will be a string in single quotes and will be either 'right',
'left', 'mid' or 'trap'; if not, an appropriate error message will be dis-
played.
• The input color will specify which color will be used to fill in the rectangles.
It could be a vector or a string name for a color. No error checking will be
done on this input.
The function will have 1 output; the calculated Riemann sum (using the right
Riemann sum if sumType = 'right', the left Riemann sum if sumType = 'left',
the midpoint rule if sumType = 'mid', and the trapezoidal rule if sumType =
'trap'). The value that is the output should NOT be symbolic—thus you may
need to use the double command.
The function will also plot the rule (depending on the value of sumType) of y = f (x)
from x = a to x = b using n subdivisions. You will use the fill command. Both the
edges of the rectangles/trapezoids and the function y = f (x) will be plotted in black.
190 Programming Mathematics Using MATLAB®
There will be no titles, axis labels, or other axis commands within the function; the
user can add these outside of the function.
2. For f (x) = sin4 (π x) + 2x, figure out the following by hand on paper and/or using
MATLAB to help with some calculations. Any calculations not done by hand should
be shown in MATLAB (“show your work”).
3
(a) Approximate f (x) dx using a left Riemann sum and n = 4.
1 3
(b) Approximate f (x) dx using a right Riemann sum and n = 4.
1 3
(c) Approximate f (x) dx using a midpoint rule and n = 4.
1 3
(d) Approximate f (x) dx using a trapezoidal rule and n = 4.
1
3. (a) Use the subplot command and your function to show all four Riemann
3
sums with n = 4 on the same figure using your RSum function for f (x) dx
1
using f (x) = sin (π x) + 2x. This will be a 2 × 2 figure where the top row
4
will be the left and right Riemann sums and the second row will be the
midpoint rule and trapezoidal rule. Let the left Riemann sum be in MyGreen
([0, 0.4078, 0.3412]), the right Riemann sum in yellow, the midpoint rule in
red with alpha(0.3), and the trapezoidal rule in gray ([0.75, 0.75, 0.75]).
Make sure you add titles specifying which rule is which.
(b) Compare the answers you get from your function with your answers in the
previous problem. Are they what you expected?
4. Use the subplot command to plot the one of the rules (your choice for the color
and rule but use the same for all four within these subplots) using your RSum function
3
on a figure with 2 × 2 subplots: n = 4, n = 8, n = 30, n = 75 for (sin4 (π x)+ 2x) dx.
1
5. Create a function SRule that takes as input a function fstring, a, b, and n.
• The input fstring is a string for the function f (x) in single quotes using stan-
dard MATLAB notation WITHOUT component-wise operations, just as in
RSum. No error check is done on this input.
• The inputs a and b are the lower and upper bounds, respectively for the integra-
tion. An error check will check that a <b; if not, an appropriate error message
will be displayed.
• The input n will be the number of rectangles/subintervals that will be made for
the Simpson rule. An error check will check that n is a positive EVEN integer;
if not, an appropriate error message will be displayed.
The commands syms, str2sym, sum, subs, and double will be useful or necessary.
The output of the function will be the approximation of the integral of f (x) from a
Numerical Integration 191
to b using the Simpson rule on the given n. Just as in the RSum function, it should
return a numerical approximation so you may need to use the double command.
6. Create a function SPlot.m that has the same inputs (and error checks) as SRule
in the above exercise. This function will plot the Simpson rule of y = f (x), from
x = a to x = b using n subdivisions to create a figure similar to Fig. 11.5. You will
use the syms, str2sym, polyfit, and the polyval commands. The approximating
quadratics will be plotted without a color specified (so that the graphs cycle through
the colors), and the curve y = f (x) will be in black. Have the domains in the plots for
the approximating quadratics be 0.05 beyond the xk used in the approximations. For
example, if the first quadratic is approximating the curve from 1 to 1.5, then have
the plot of the quadratic be from 0.95 to 1.55. You will also plot the subdivisions in
black; these will be vertical lines from (xk , 0) to (xk , yk ) for each of x0 , x1 , . . . , xn .
3
7. We will investigate Simpson’s rule to estimate f (x) dx for f (x) = sin4 (π x) + 2x,
1
above with n = 2 and n = 4. For the subdivisions, figure out what the FIRST ap-
proximating quadratics would be. This should be done on paper and turned in,
showing all work, explaining it clearly, and using exact values. Any calculations us-
ing technology should be done in MATLAB. The answers for the approximating
quadratics (and the subintervals they are for) should be written clearly. Use the in-
terval [−h, h] and figure out the coefficients A, B, and C based on the values of
yk , yk+1 , and yk+2 from the notes. That quadratic is based on the middle x-value
equaling 0. Use a horizontal shift so that the middle value is now at xk+1 .
(a) Figure out the FIRST approximating quadratic for n = 2.
(b) Figure out the FIRST approximating quadratic for n = 4.
8. Check your answers in the above problem using the command polyfit and even
poly2sym, clearly labeling your answers.
(a) Check for n = 2.
(b) Check for n = 4. 3
9. Use your SRule function to approximate (sin4 (π x) + 2x) dx with the Simpson
1
rule using n = 2, n = 4, n = 8, and n = 16. Also, use subplot as in previous exercises
with your SPlot to visualize the Simpson rule for these four numerical approxima-
tions.
CHAPTER 12
Scalars are commonly the set of real numbers (called a real vector space) or the set
of complex numbers (called a complex vector space).
Examples of vector spaces
1. Rn : Euclidean vector space of Rn
2. Mmn : the set of m × n matrices.
3. The set of all functions with domain R:
• Addition is defined pointwise: f + g = h is the function
h(x) = (f + g)(x) = f (x) + g(x).
• af is defined as the function af (x).
Note: you could define a different domain instead of R. You could also change it to
be all continuous functions on domain D, all differentiable functions with domain D,
etc.
4. Pn : the set of all real-polynomials of degree ≤ n.
5. C n [a, b]: the set of all functions whose nth derivatives exist and are continuous on
[a, b] (thus the function, first derivative, second derivative, . . . , nth derivative are all
continuous on [a, b]).
6. The set of all functions that satisfy the differential equation 3y − y + y = 0.
12.1.2 Subspaces
v = a1 v1 + a2 v2 + · · · + am vm .
Example 12.2.1. Is the first vector a linear combination of the other vectors? If so,
write the linear combination.
(a) x = (−11, 9, −3); v1 =(1, −1,1), v2 =(2, 1,4), v3 =(−2, 3,
1).
1 −25 2 0 0 1 1 5
(b) x = ; v1 = , v2 = , v3 = .
8 −13 1 −1 3 4 −1 2
(c) f (x) = 2x2 + x − 3; g(x) = x2 − x + 1, h(x) = x2 + 2x − 2.
f1 = 1, f2 = x, f3 = x2 + x, f4 = x2 − 1.
U = span S = span{v1 , v2 , . . . vm }.
(b) v = (1, 1, 2), S = {(0, 1, 0), (3, 5, 6), (1, 2, 1)} (no).
Example 12.2.5. Give examples of three other functions in the subspace span S,
where
S = {2x + 1, 3x2 + x − 3}.
c1 v1 + c2 v2 + · · · + cm vm = 0. (*)
Example 12.3.1. Are the following sets of vectors linearly independent or linearly
dependent?
(a) {1, x, x2 } ⊂ P2 .
{x2 + x3
(b) } ⊂P3 .
1 0 0 0
(c) , ⊂ M22 .
0 1 0 1
(d) {f1 , f2 , f3 , f4 } ⊂ P3 where
f1 = 1, f2 = x, f3 = x3 + x, and f4 = x2 − 1.
Proof. (⇐=) Assume the set of vectors S = {v1 , v2 , . . . vm } are LI. Let v ∈ V . Since V =
span S, by definition of span we can write v as a linear combo of these vectors. Suppose
we have two ways of writing v as a linear combination:
v= ak vk , v= bk vk .
Then we have
(ak − bk )vk = 0.
But since these vectors are LI, ak − bk = 0 for all k. Thus ak = bk for all k, and there’s
only one way of expressing v as a linear combo of the vectors in S.
( =⇒ ) Let v ∈ V be arbitrary and we are given that v can be written uniquely as a
linear combo of vectors in S. Since 0 ∈ V , then 0 can be written uniquely as a linear
combination of vectors in S. We know
0= 0vk ,
so this must be the only solution, thus the vectors in S are linear independent.
12.3.2 Bases
Definition 12.3.2. Let V be a vector space. Let S = {v1 , v2 , . . . , vm } ⊂
V be such that
1. S is a linearly independent set of vectors, and
2. V = span S.
Then S is called a BASIS for V .
Thus if S is a basis for V , each vector in V can be expressed
uniquely as a linear combination of vectors in S.
f1 = 1, f2 = x, f3 = x2 , f4 = x3 .
Proof. Let ck wk = 0. Since {v1 , v2 , . . . , vn } is a basis for V , each of the vectors wk can
be written as a linear combo of these basis vectors.
Thus we get
ck (ak1 v1 + ak2 v2 + · · · + akn vn ) = 0.
If we rearrange, we get
Thus a11 c1 + a21 c2 + · · · + am1 cm = 0, etc. Notice that we have m variables and n equations,
but n < m so at least one of the variables is free. Therefore there are nontrivial solutions
for the ck so the set is LD.
Corollary 12.3.1. All bases for a vector space V have the same num-
ber of vectors.
Example 12.3.6. P = set of all polynomials and C 2 [0, 1], etc. are infinite dimensional
vector spaces.
The Gram–Schmidt Process 199
⎡ √ ⎤ ⎡ √ ⎤ ⎡ ⎤
1/ 2 −1/ 2 0
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
Example 12.3.8. ⎣ 0√ ⎦ , ⎣ √ 0 ⎦ , ⎣1⎦ are linearly independent in R3 (check
1/ 2 1 2 0
it!) so the set of these vectors form a basis for R3 .
S ∪ {vm+1 , vm+2 , . . . , vn }
1 0 0 0
Example 12.3.9. , form a linearly independent set in the space of
0 0 0 1
lower triangular matrices. We need one more to form a basis:
0 0
.
5 0
200 Programming Mathematics Using MATLAB®
12.4. Rank
Definition 12.4.2. The dimension of the row space and the column
space of a matrix A is called the RANK OF A, denoted by rank(A).
Proof. Since A and B are row equivalent, the rows of B can be obtained from the rows
of A through elementary row operations, and vice versa. Thus each row of B is a linear
combination of the rows of A. Thus the row vectors of B are in the row space of A, and
vice versa. Thus the row spaces are the same.
Any vector u = 0 can be normalized; i.e., a unit vector v can be found in the same
direction as u:
1
v= u.
u
⎧ ⎡ ⎤ ⎡ ⎤ ⎡ ⎤⎫
⎪
⎨ 1 1 1 ⎪⎬
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
Example 12.5.1. S = u1 = ⎣−1⎦ , u2 = ⎣2⎦ , u3 = ⎣ 0 ⎦ ,
⎪
⎩ ⎪
1 1 −1 ⎭
u1 · u2 = 0,
u1 · u3 = 0,
u2 · u3 = 0,
=⇒ S is an orthogonal set.
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
√1 √1 0
⎢ 2
⎥ ⎢ 2
⎥ ⎢ ⎥
Example 12.5.2. The vectors v1 = ⎢ 1 ⎥
⎣− √ 2 ⎦ , v2 = ⎢ 1 ⎥
⎣ √2 ⎦ , v3 = ⎢ ⎥
⎣ 0 ⎦ form an
0 0 −1
orthonormal set.
(c1 v1 + c2 v2 + · · · + cm vm ) · vk = 0 · vk ,
c1 v1 · vk + c2 v2 · vk + · · · + cm vm · vk = 0;
ck vk · vk = 0.
Example 12.5.3. The set S from Example 12.5.1 are vectors in R3 . They are orthog-
onal; thus they are LI. We know dim(R3 ) = 3 thus S is a basis for R3 and since they
√
are
orthogonal, S is an orthogonal basis for R3 . Is S an orthonormal basis?
u1
= 3 so
no. (But one could form one from S... remember how?)
Example 12.5.4. The standard bases for Rn , Mmn , and Pn are all orthonormal. The
vectors in Example 12.5.2 above are another example of an orthonormal basis for R3 .
c1 v1 + c2 v2 + · · · + cn vn = u.
(c1 v1 + c2 v2 + · · · + cn vn ) = u · vk ,
···
ck vk · vk = u · vk ,
ck = u · vk .
Example 12.5.5. Using the above orthonormal basis for R3 from Example 12.5.2,
find the coefficients for (−1, 2, −3).
u1 = w1 ,
u1 · w2
u2 = w2 − u1 ,
u1
2
u1 · w3 u2 · w3
u3 = w3 − u1 − u2 ,
u1
2
u2
2
..
.
i−1
uk · wi
ui = wi − uk .
uk
2
k=1
Proof. The proof is in linear algebra books—read it. Basically the numbers in front of
the uk render each vector orthogonal to the previous ones.
The Gram–Schmidt Process 205
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
1 2 1
⎢0⎥ ⎢1⎥ ⎢−1⎥
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
Example 12.5.6. w1 = ⎢ ⎥ , w2 = ⎢ ⎥ , w3 = ⎢ ⎥,
⎣1⎦ ⎣0⎦ ⎣0⎦
2 2 1
⎡ ⎤
1
⎢0⎥
⎢ ⎥
u1 = w1 = ⎢ ⎥ ,
⎣1⎦
2
u1 · w2 2 + 0 + 0 + 4 6
= = = 1,
u1
2 1+1+4 6
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
2 1 1
⎢1⎥ ⎢0⎥ ⎢ 1 ⎥
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
u2 = w2 − (1)u1 = ⎢ ⎥ − ⎢ ⎥ = ⎢ ⎥ ,
⎣0⎦ ⎣1⎦ ⎣−1⎦
2 2 0
u1 · w3 1 + 0 + 0 + 2 1
= = ,
u1
2 6 2
u2 · w3 1 − 1 + 0 + 0
= = 0,
u2
2 3
⎡ ⎤ ⎡ ⎤
1
1 2
⎢ ⎥ ⎢ ⎥
1 ⎢−1⎥ ⎢ 0 ⎥
u3 = w3 − u1 − 0u2 = ⎢ ⎥ − ⎢ 1 ⎥
2 ⎣ 0 ⎦ ⎣2⎦
1 1
⎡ ⎤
1
2
⎢ −1 ⎥
⎢ ⎥
= ⎢ 1⎥,
⎣− 2 ⎦
0
⎧⎡ ⎤ ⎡ ⎤ ⎡ ⎤⎫
⎪
⎪ 1 1 1 ⎪
⎪
⎪
⎨⎢0⎥ ⎢1⎥ ⎢ −1 ⎥⎪
2
⎬
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢ ⎥, ⎢ ⎥, ⎢ 1⎥ .
⎪⎣1⎦
⎪ ⎣−1⎦ ⎪
⎣− 2 ⎦⎪
⎪
⎩ 2 ⎪
0 0 ⎭
√ √ √
What if one wanted an orthonormal basis?
u1
= 6,
u2
= 3,
u3
= 2
6
...
x = a1 b1 + a2 b2 + · · · + ap bp
206 Programming Mathematics Using MATLAB®
where these ai are unique. These ai are called the COORDINATES of x with respect to
the basis B.
⎧⎡ ⎤ ⎡ ⎤ ⎡ ⎤⎫
⎪
⎨ 2 1 1 ⎪⎬
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
Example 12.5.7. B = ⎣ 1 ⎦, ⎣2⎦ , ⎣−1⎦ is a basis for R3 but not an or-
⎪
⎩ −1 ⎪
0 1 ⎭
thogonal basis. ⎡ ⎤
3
⎢ ⎥
Express x = ⎣ 2 ⎦ in terms of B. We would have to solve the system ab1 + bb2 +
−1
cb3 = x:
rref 7 1 1
b1 b2 b3 x −−→ a = , b = , c = .
6 2 6
x = a1 b1 + a2 b2 + · · · + ap bp ,
bi x = · · · = a1 bTi b1 + a2 bTi b2 + · · · + ai bTi bi
T
+ · · · + ap bTi bp ,
a3 · 0,
=⇒ ai bTi bi = ai
bi
2 = bTi x
bTi x bi · x
=⇒ ai = = .
bi
2
bi
2
Thus if a basis is orthonormal, the coefficients with respect to that basis are
ai = bTi x = bi · x.
⎡ ⎤ ⎧⎡ ⎤ ⎡ ⎤ ⎡ ⎤ ⎫
−1 ⎪
⎨ 1 −1 0 ⎪
⎬
⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥
Example 12.5.8. x = ⎣ 1 ⎦, B = ⎣0⎦ , ⎣ 0 ⎦ , ⎣1⎦ ; B is an orthogonal basis.
⎪
⎩ 1 ⎪
2 1 0 ⎭
Write x in terms of B,
b 1 · x −1 + 2 1
a1 = = = ,
b1
2 2 2
b2 · x 1 + 2 3
a2 = = = ,
b2
2 2 2
b2 · x 1
a3 = = = 1,
b3
2 1
1 3
x = b1 + b2 + b3 .
2 2
The Gram–Schmidt Process 207
Besides finding “coordinates” more easily, there are many other reasons why one
would want orthogonal or orthonormal bases for spaces and subspaces.
Example 12.5.9. In this example we will visualize the difference between bases in
R2 . Let
1 4
b1 = and b2 = .
1 3
These vectors are linearly independent, so they form a basis for R2 .
If we graph these two vectors, we clearly see that the vectors are not orthogonal and
are of different lengths (see Fig. 12.1).
Using the Gram–Schmidt process, we get an orthogonal basis of
1
1 2
u1 = and u2 = .
1 − 12
If we graph these vectors, we clearly see these are now orthogonal (see Fig. 12.2).
If we normalize these vectors, we get the following orthonormal basis for R2 :
√1 √1
2 2
v1 = and v2 = .
√1
2
− √12
Graphing these vectors along with the unit circle we clearly see these vectors are not
only orthogonal but also of length 1 (see Fig. 12.3).
208 Programming Mathematics Using MATLAB®
Example 12.5.10. In this example we will visualize the difference between bases for
R3 . Let
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
4 1 1
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
b1 = ⎣ 1 ⎦ , b2 = ⎣1⎦ , and b3 = ⎣−1⎦ .
−1 0 1
⎡ ⎤ ⎡ 1⎤ ⎡ ⎤
4 −9 5
11
⎢ ⎥ ⎢ 13 ⎥ ⎢ 5⎥
u1 = ⎢ ⎥
⎣ 1 ⎦, u2 = ⎣ 18 ⎥
⎢
⎦, u3 = ⎢ ⎥
⎣− 11 ⎦ .
−1 5
18
15
11
If we graph these and change the view, we can see these are orthogonal vectors (see
Fig. 12.5).
If we take these orthogonal basis vectors and normalize them, we get the following
orthonormal basis. The unit sphere is also shown so we can see that the vectors are
indeed of length 1 (see Fig. 12.6).
210 Programming Mathematics Using MATLAB®
Example 12.1.2
Example 12.2.1
(a) Yes. x = v1 − 2v2 + 4v3 .
(b) Yes. x = 3v1 + 0v2 − 5v3 .
(c) No.
Example 12.2.4
Example 12.3.1
Example 12.3.7
12.7. Exercises
Note that all ERROR CHECKS within your functions should use the error command
and display a meaningful error message.
1. Finish the function gs.m that is found on the text website. It will have as input a
m × n matrix in which the columns of the matrix are linearly independent; thus
the columns of the matrix form a basis for the column space W ⊆ Rm . (We will
not check for this linearly independence—we will assume the user has figured this
out correctly.) The function will return a matrix in which the columns form an
orthogonal basis for the column space W . The function will use the Gram–Schmidt
process to create the vectors (output matrix).
2. Finish the function gsON.m that is found on the text website. It will take as input a
m × n matrix in which the columns of the matrix are linearly independent as in the
above problem. (Again, we will not check for this linearly independence—we will
assume the user has figured this out correctly.) The function will return a matrix in
which the columns form an orthonormal basis for the column space W . This function
may use the function gs.m.
3. For this problem, you will show an example of a basis for R2 using the Gram–
Schmidt process.
(a) Use the randi command to generate a 2 × 2 matrix with integers from −100
to 100. If the determinant of this matrix equals 0, generate another one until
you get a matrix with nonzero determinant (the use of while may be useful
here). The columns of this matrix form a basis for R2 and will be the in-
put matrix for gs and gsON. Make the matrix used output to the command
window.
(b) Use your gs function to generate an orthogonal basis from this basis.
(c) Use your gsON function to generate an orthonormal basis from this basis.
212 Programming Mathematics Using MATLAB®
(d) Using subplots, generate a 2 × 2 matrix of plots of these vectors using the
plotVec function from Exercise 4 in Chapter 6. The first graph will have
your original 2 column vectors plotted. The second graph will have the or-
thogonal basis vectors plotted, and the third graph will have the orthonormal
basis vectors plotted. The fourth graph will have the orthonormal basis vec-
tors plotted along with the unit circle (in blue).
For the first two graphs the range on the axes should be from −100 to 100,
and the third and fourth graphs from −1 to 1. The first graph the vectors
should be in blue, the second in red and the third/fourth in black or another
color of your choosing. Make the LineWidth 2 on all of them, have the
grid on and use the axis equal command in all of the subplots.
4. For this problem, you will show an example of a basis for R3 using the Gram–
Schmidt process.
(a) Use the randi command to generate a 3 × 3 matrix with integers from −100
to 100. If the determinant of this matrix equals 0, generate another one un-
til you get a matrix with nonzero determinant (the use of while may be
useful here). The columns of this matrix form a basis for R3 and will be the
input matrix for gs and gsON. Have the matrix used output to the command
window.
(b) Use your gs function to generate an orthogonal basis from this basis.
(c) Use your gsON function to generate an orthonormal basis from this basis.
(d) Using subplots, generate a 2 × 2 matrix of plots of these vectors using the
plotVec function from Exercise 4 in Chapter 6. The first graph will have
your original 3 column vectors plotted. The second graph will have the or-
thogonal basis vectors plotted, and the third and fourth graphs will have the
orthonormal basis vectors plotted. The fourth graph will also have the unit
sphere plotted using the commands sphere, mesh and specify a color for the
EdgeColor. Also, in order to see the vectors inside the sphere, have the com-
mand hidden off after the mesh command and you may want to set the
alpha value JUST FOR THE MESH COMMAND FOR THE SPHERE
set to a number close to 0 (transparent).
For the first two graphs the range on the axes should be from −100 to 100,
and the third from −1 to 1. The first graph the vectors should be in blue,
the second in red and the third/fourth in black. Make the LineWidth 2 on
all of them, have the grid on and use the axis equal command in all of the
subplots.
5. For this problem we will generate two non-colinear vectors in 3D, plot the plane
containing these vectors, the vectors, and the orthogonal and orthonormal basis
vectors for this plane. Because of the subplot above, you may want to start off this
section of code with clf. Generate a random 3 × 2 matrix with values between
The Gram–Schmidt Process 213
−2 and 2 (integers or real numbers—your choice). If the cross product of the two
columns equals the zero column vector, keep generating a new random matrix
until the cross product is nonzero. Plot the plane that contains these two vectors
using plotPlane (from Exercise 5 in Chapter 6), with domain from −2 to 2, and
EdgeColor a gray color. Using gs and gsON, find the orthogonal basis vectors and
orthonormal basis vectors for this same plane. Plot the original vectors in a blue
color, the orthogonal vectors in a reddish color and dotted, and the orthonormal
vectors in black. Experiment with the LineWidth so you can see the vectors.
NOTE: For all of the above 3D graphs, you may use the view command so you can
see all of the vectors and you compare between the original and orthogonal, but each
time you rerun it the best view needed may be different because of the different random
vectors generated. Do not worry if the 3D view on any published page or turned in
work is not ideal.
APPENDIX A
Link 1: basicMFile.m
% Example of Basic Script file
215
216 Publishing and Live Scripts
Link 2: publishMFile1.m
%% Example of Basic Script file
% Lisa Oberbroeckling, 2019
clc
x=linspace(-pi,pi);
y=sin(x);
plot(x,y)
%% second problem
A=[1 2 3;4 5 6;7 8 9];
B=[A(1,:); -4*A(1,:) + A(2,:); A(3,:)]
B2=[B(1,:); B(2,:); -7*B(1,:) + B(3,:)]
C=[B2(1,:); -1/3*B2(2,:); B2(3,:)]
The above is better than the published page without sections, but can be better. We
may want the page to start with a title. This is done by adding a line “%%” after our title
(and another comment line(s) for other introductory text, like my name).
LINK 3: publishMFile2.m
%% Example of Basic Script file
% Lisa Oberbroeckling, 2019
%%
clc
x=linspace(-pi,pi);
y=sin(x);
plot(x,y)
%% second problem
A=[1 2 3;4 5 6;7 8 9];
B=[A(1,:); -4*A(1,:) + A(2,:); A(3,:)]
B2=[B(1,:); B(2,:); -7*B(1,:) + B(3,:)]
C=[B2(1,:); -1/3*B2(2,:); B2(3,:)]
If you look at the published webpage, you will notice that we have a section link and
title for the “second problem” but not for the first. So we probably want to change line
3 to include a section title:
218 Publishing and Live Scripts
LINK 4: publishMFile3.m
%% Example of Basic Script file
% Lisa Oberbroeckling, 2019
%% first problem
clc
x=linspace(-pi,pi);
y=sin(x);
plot(x,y)
%% second problem
A=[1 2 3;4 5 6;7 8 9];
B=[A(1,:); -4*A(1,:) + A(2,:); A(3,:)]
B2=[B(1,:); B(2,:); -7*B(1,:) + B(3,:)]
C=[B2(1,:); -1/3*B2(2,:); B2(3,:)]
When publishing m-files, each time a new section is started, MATLAB displays the
output created by the commands of the previous section. The difference between
publishMFile3.html and publishMFile4.html is where the output is displayed for the
second problem.
Another important place to insert a section break is when you want to have text follow-
ing MATLAB commands, but within the same section. If you just include comments
after the MATLAB commands, they will be formatted as comments within the dis-
played code, not as text. Instead, insert a section break (without a section title) and then
the comment block that will be the text:
Publishing and Live Scripts 219
Note that you can also have section titles without having section breaks. This is done
by having the line start with %%%” along with the section text. This will have the text
and/or MATLAB commands be within the sections, but the output of those commands
at the next section break, which may not have the desired effect.
Using sections is especially important for m-files with multiple plots. Remember, MAT-
LAB only shows the last plotting command (like plot, ..., mesh, surf, etc.). You can
have multiple commands appear on the same figure by using the hold on and hold
off commands. But if you want to display multiple figures (not in the same window),
you have to either use the pause command or the figure command. This first example
uses the pause command:
LINK 6: publishMFile5.m
%% Example of Basic Script with pause
% Lisa Oberbroeckling, 2019
%%
x=linspace(-pi,pi);
y=sin(x);
plot(x,y)
hold on
y=cos(x);
plot(x,y,'r')
hold off
220 Publishing and Live Scripts
title('First Plot')
pause
[x,y]=meshgrid(linspace(-10,10));
z=sin(x).*cos(y);
mesh(x,y,z)
xlabel('x'),ylabel('y'),zlabel('z')
title('Second Plot')
If you run the file publishMFile5.m, the first figure will appear and then MATLAB
will be paused. The second will appear after any key is pressed. When this is published,
even the publishing will be on pause after the first figure is created until you press a key.
But if you look at the webpage, only the last figure is actually shown on the webpage.
As discussed above, when publishing, MATLAB runs each section as a block and then
displays any output. At the end of the section the only output that MATLAB sees
as being created by the section of commands is the second figure. The second figure
replaces the first figure, so it is not shown on the webpage. Thus, we need to create
a section for each figure we want on the webpage. When we publish the m-file, we
have to remember to “press any key” for the publishing can continue, which is really
annoying so you may want to take the pause command out or comment it out. In the
following example we created a new section without a section title.
LINK 7: publishMFile5b.m
%% Example of Basic Script with pause
% Lisa Oberbroeckling, 2019
%%
close all
clc
% first plot
x=linspace(-pi,pi);
y=sin(x);
plot(x,y)
hold on
y=cos(x);
plot(x,y,'r')
hold off
title('First Plot')
% pause
%%
[x,y]=meshgrid(linspace(-10,10));
z=sin(x).*cos(y);
mesh(x,y,z)
xlabel('x'),ylabel('y'),zlabel('z')
title('Second Plot')
Publishing and Live Scripts 221
LINK 8: publishMFile6.m
%% Example of Basic Script with figure
% Lisa Oberbroeckling, 2019
%%
close all
clc
% first plot
figure(1)
x=linspace(-pi,pi);
y=sin(x);
hold on
y=cos(x);
plot(x,y,'r')
hold off
plot(x,y, 'r')
title('First Plot')
% Second plot
figure(2)
[x,y]=meshgrid(linspace(-10,10));
z=sin(x).*cos(y);
mesh(x,y,z)
xlabel('x'),ylabel('y'),zlabel('z')
title('Second Plot')
% third plot
figure(3)
[x,y]=meshgrid(linspace(-10,10));
z=x.*cos(y);
mesh(x,y,z)
xlabel('x'),ylabel('y'),zlabel('z')
title('Third Plot')
% fourth plot
figure(4)
[x,y]=meshgrid(linspace(-10,10));
z=x.*y;
mesh(x,y,z)
xlabel('x'),ylabel('y'),zlabel('z')
title('Fourth Plot')
When the above file is published, it puts each figure side-by-side on one line. Depending
on how many figures you have this may not have the desired effect, so you may want to
have each figure within its own section instead.
LINK 9: publishMFile6b.m
%% Example of Basic Script with figure
% Lisa Oberbroeckling, 2019
222 Publishing and Live Scripts
%%
close all
clc
%% first plot
figure(1)
x=linspace(-pi,pi);
y=sin(x);
hold on
y=cos(x);
plot(x,y,'r')
hold off
plot(x,y, 'r')
title('First Plot')
%% Second plot
figure(2)
[x,y]=meshgrid(linspace(-10,10));
z=sin(x).*cos(y);
mesh(x,y,z)
xlabel('x'),ylabel('y'),zlabel('z')
title('Second Plot')
%% third plot
figure(3)
[x,y]=meshgrid(linspace(-10,10));
z=x.*cos(y);
mesh(x,y,z)
xlabel('x'),ylabel('y'),zlabel('z')
title('Third Plot')
%% fourth plot
figure(4)
[x,y]=meshgrid(linspace(-10,10));
z=x.*y;
mesh(x,y,z)
xlabel('x'),ylabel('y'),zlabel('z')
title('Fourth Plot')
Note that you can also use sections for running/debugging code. This topic is only
covered briefly.
2. Within the editor, select the “Run Section” or “Run and Advance” buttons on the
Editor Tab.
WARNING: when you run (evaluate) a section, the file may not be saved automatically
as it is when you run the entire m-file!
Text can be formatted to be bold, italic, monospaced, or combinations such as bold and
italic.
A.5.2 Lists
One can have an unordered, or bulleted list.
Keep in mind that you must have a section break before the list, with or without a
section title. You also must have a blank comment line to end the list. Here is another
example.
You can also have an ordered (numbered list) using the same formatting as above, but
with “#” instead of “∗” for each list item.
As in the bulleted list, one must have a section break, with or without a section title.
Second example without section title:
%
% Here's an example of using the URL as
% the text of the link: <http://www.mathworks.com>
%
LINKING THE M-FILE: It may be nice (required!) to link the m-file that was
published to create the webpage. The easiest way to do it is like it is done below rather
than using the entire URL.
The “../” before the filename means to go back one folder from where the HTML file
is located, which is where the m-file is located.
IMPORTANT: the text within the “<” and “>” must be on the same line within
the file. The editor might automatically wrap the text if the URL and/or the text for
the link is long. If this is the case, you must go back and make it one line. Otherwise,
the link will be broken!
The image must be on its own line; no text can appear before or after it for the image
to be shown correctly on the page. Also note that the above is assuming the file for the
image is located in the “html” folder into which the HTML file the M-file produced is
located.
Then you change the words “PREFORMATTED” AND “TEXT” and add lines if
necessary:
These images make the formulas appear blurry and/or small, and as mentioned above,
not every symbol will display correctly. Also, it could make the webpage slower to load
and would not be as accessible. Thus it may be better to use MathJax if creating a
webpage. If there is a need for a lot of LATEX or more complicated math typesetting,
consider publishing it as a LATEX file.
APPENDIX B
Final Projects
B.1. Ciphers
Create function(s) that create a substitution cipher encoder and decoder and a transpo-
sition cipher encoder and decoder, plus functions that demonstrate these ciphers. Some
useful MATLAB® functions: randperm, double, char, and reshape.
229
230 Final Projects
To demonstrate the above functions, create another function that will create tables
that show the substitution cipher. It will as input take the “key” and create tables of the
character and what that character looks like in the encoded message. Have one table be
the characters (may split up into multiple tables for visual purposes), another table the
numbers, and one or two tables the letters (split between upper and lower? you will be
the judge). Thus your output may look like this (example cipher shown):
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
-----------------------------------------------------
D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ]
a b c d e f g h i j k l m n o p q r s t u v w x y z
-----------------------------------------------------
d e f g h i j k l m n o p q r s t u v w x y z { | }
0 1 2 3 4 5 6 7 8 9
---------------------
3 4 5 6 7 8 9 : ; <
This would signify that for every “A” in the original message, it is encoded as “D”,
every space becomes the character “#”, etc. Make these tables visually pleasing in the
output window (using fprintf, etc.).
Another function will demonstrate the columnar transposition. It will take as input
the original message and the key. The function will display the original message, the
matrix of characters, the permuted matrix of characters, and the encoded message.
These displays should be formatted such that if the messages are long, then no more
than 50 characters are displayed on one line.
Your report should include a basic history of these types of ciphers, examples, pros
and cons to using these types of ciphers, and other variations of the ciphers.
B.3.1 Linearization
Create a function called myLinear in which the function takes a string that is the
function f (x), and a value a. Using the commands syms, str2sym, subs, and diff,
your function will calculate the tangent line to y = f (x) at the point x = a. The function
will return the linearization L (x) = f (a)(x − a) + f (a) (as a symbolic function).
In a separate script file that you may publish, you will use your function to do the
following problems.
√
1. Consider the function f (x) = 3 1 + x.
(a) Use your myLinear function to find the linearization of f (x) at the point
x = 0. Careful! You may have to use a different function than (1+x)^(1/3)
or nthroot(1+x,3) in order to make it work (surd?). Display the √
answer.
√
(b) Use myLinear function to approximate the values of 3 0.95 and 3 1.1.
(c) Graph the function y = f (x), the tangent line at x√= 0, and the points cor-
√
responding to the approximations of 3 0.95 and 3 1.1 on the same graph.
Create several graphs, zooming in to see the difference between the graph
and the tangent line at these points. Make sure you create a legend to make
things clearer.
2. Let f (x) = (x − 1)2 , g(x) = e−2x , and h(x) = 1 + ln(1 − 2x).
(a) Use your myLinear function to find the linearizations of f , g, and h at a = 0.
What do you notice? Why did this happen?
(b) Graph f , g, h, and the tangent lines on one graph. Create a legend in or-
der to tell which is which. For which function is the linearization a better
approximation (and for approximately what x-values)? Create several graphs,
zooming in, to support your answers.
• the desired accuracy (ERROR CHECK: this number should be positive; if not, an
appropriate error message should be displayed using the error command),
• and the maximum number of iterations allowed (so it will stop if accuracy cannot
be reached) (ERROR CHECK: this number should be a positive integer; if not,
an appropriate error message should be displayed using the error command).
The function uses the Symbolic Math Toolbox (syms, diff, etc.) to convert the given
string for the function to a symbolic function and to calculate the derivative of the given
function f . Your HELP lines should make clear what the inputs are and the order. The
output will be the approximation to the solution of f (x) = 0. Your code will iterate
until the absolute value of the difference between the last two iterations is less than the
desired tolerance/accuracy OR the maximum number of iterations has been reached.
In either case, an appropriate message should be printed on the screen so the
user knows if desired accuracy has been reached or not. The message should include
how many iterations were completed. Use either disp or fprintf, and/or sprintf for
this message; experiment with this. The output of your function is the LAST iterate. In
other words, if x7 was calculated to determine that x6 is accurate enough, still output x7
and state that 7 iterations were calculated. If the derivative ever equals 0 at any iteration,
an appropriate error message should be displayed and the function will stop (use the
error command).
The following problems will demonstrate/use Newton’s method. The code for these
problems will be in the same script file as the problems on Linearization.
3. Consider the function f (x) = x4 − x − 1.
(a) Use your newton function to find x2 using x1 = 1 to find an approximation
to a root of f (x).
(b) Graph y = f (x), the tangent line at x1 = 1, and the tangent line at x2 to see
how the roots of each subsequent tangent line gets closer to the root. Make
sure you have a legend and appropriate axes to be able to see √ everything.
4. Use your function newton to find all roots to the equation earctan(x) = x3 + 1 correct
to eight decimal places (make sure all decimal places are displayed). In order to do
this, first create an appropriate plot to figure out what you are going to use for your
initial approximations of x1 for each root.
5. To demonstrate the importance of that first guess, consider the function f (x) =
x3 − x − 1.
(a) Use your function newton to find a root of the equation
√
correct to six decimal
places using an initial approximation of x1 = 1/ 3. State how many iterations
were needed or why Newton’s method did not work in this case.
(b) Use your function newton to find a root of the equation correct to six decimal
places using an initial approximation of x1 = 0.57. State how many iterations
were needed or why Newton’s method did not work in this case.
234 Final Projects
(c) Use your function newton to find a root of the equation correct to six decimal
places using an initial approximation of x1 = 0.6. State how many iterations
were needed or why Newton’s method did not work in this case.
(d) Use your function newton to find a root of the equation correct to six decimal
places using an initial approximation of x1 = 1. State how many iterations
were needed or why Newton’s method did not work in this case. √
(e) Graph the function y = f (x), and the tangent lines at x = 1/ 3, x = 0.57,
x = 0.6, and x = 1. Does the graph explain your answers to the above? Make
sure your graph has a legend and appropriate axes (or create a second graph
with appropriate axes) to see what is going on and support your claims.
NOTE: if any of the above return an error, you may need to comment out that
code so the rest of your script can run afterwards (keep the code in there to “show
your work” and mention something in the comments/text of your report).
Entering a matrix
Rows of a matrix are separated by semicolons (;) and entries within a row are
separated by either commas or spaces. Brackets enclose the matrix. For example, you
could use either of the following commands to define the same matrix.
A=[1,2,-1,2,0;2,1,1,-1,0;3,-1,-2,3,0]
OR
A=[1 2 -1 2 0;2 1 1 -1 0;3 -1 -2 3 0].
Semicolons
Semicolons “;” at the end of a command suppress output to the command window.
See the difference with the above commands with and without a semicolon at the end
of the line.
There are three functions that were written for some of the exercises below. You have
the ability to write your own, and may be asked to write functions later or in another
course. In order for these “hand-written” functions to run in MATLAB® ,
they need to be in the folder/directory you are working in. So you need to
pay attention to the “Current Folder” on the MATLAB screen above the editor and
command window and/or to the left of the screen. You will need to save these function
files in your own folder where you will be saving, running, and possibly publishing,
your SCRIPT or LIVE SCRIPT file from. There are some naming conventions to
your functions. For example, we cannot name a function sin.m since there is already a
237
238 Linear Algebra Projects
RREF
To get a matrix already entered and named A in reduced row echelon form, just
type
rref(A)
Notice that the answer may not give the answer in exact values. You could have
MATLAB do this by using the SYMBOLIC MATH TOOLBOX. (Most versions of
MATLAB will come with this toolbox.) This is done using the function sym. For
example, type
sym(rref(A))
Notice that the resulting output is now in exact value form. REMEMBER THIS;
we will be using exact values on multiple exercises.
Another way is to use the rats function or change the format of answers to format
rat. THIS IS ONLY USEFUL IF YOUR ANSWERS AND MATRICES WILL
ONLY HAVE INTEGER OR RATIONAL NUMBERS IN THEM. For example, if
you switch to format rat, notice what happens when you enter pi. You can display
your matrix fraction, rather than decimal form by entering the following:
format rat
rref(A)
Or, without changing the format, you could enter:
rats(rref(A))
To get back to the default format, enter format or format short. To test, you can
always enter pi and see if you get 3.1416.
HELP in MATLAB
If you know a command or function name, you can always get help for it by typing
help command. For example, you can type help rref. Also, if the function files are
copied over the current directory you can type help addrow to get some help for it.
For help with MATLAB defined functions and commands you can also use the Help
menu item at the top.
Linear Algebra Projects 239
C.1.2 Exercises
These are exercises I’ve included on the first “introductory” project at various times.
I have not included all of them at once. Which exercises have been chosen and how
many are chosen depends on the textbook used and the timing of the assignment.
1. Consider the linear system below. Use MATLAB to solve the system by putting
it in RREF form but do each step separately (i.e., DON’T use the RREF com-
mand). Use the three functions swap, mult, and/or addrow found on the text
website. NOTE: In order to be able to use the functions within MATLAB, you
MUST copy the three files to your Current Folder within MATLAB.
x1 − x2 − 2x3 = −5,
6x1 − 5x2 − 7x3 = −3,
−2x1 − 6x3 = −44.
You may need to rerun your script file after each step to see what the next step
should be. In the end, you should have all steps needed to get it into RREF form.
Also, you will need to have exact values (thus the rats command may need to be
used—at every stage or at the end—you will be the judge).
2. Consider the linear system below. Use MATLAB to solve the system by putting
the augmented matrix in RREF form. You may use the rref command for this,
but make sure that exact answers are given.
3. Consider the linear system below. Use MATLAB to solve the system by putting
the augmented matrix in RREF form. You may use the rref command for this,
but make sure that exact answers are given.
x1 + x2 = −2,
x2 + x3 = 2,
x3 + x4 = 3,
x1 + x4 = −1.
4. Consider the linear system below. Use MATLAB to solve the system by putting
the augmented matrix in RREF form. You may use the rref command for this,
but make sure that exact answers are given.
5. Suppose a quadratic polynomial f (x) = ax2 + bx + c goes through the points (−1, 3),
(0, 2), and (2, 24). Using the points, write a system of linear equations to solve for
the unknown coefficients of f (x). Use MATLAB to solve this system and thus find
the polynomial by putting the augmented matrix in RREF form. You may use
the rref command for this, but make sure that exact answers are given.
6. Suppose a cubic polynomial f (x) is such that f (−1) = −6, f (−1) = 2, f (−1) =
−4, and f (−1) = 6. Using the information about the derivatives, write a linear
system to solve for the unknown coefficients of f (x). Use MATLAB to solve this
system and thus find the polynomial by putting the augmented matrix in RREF
form. You may use the rref command for this, but make sure that exact answers
are given.
7. Suppose a quartic (degree 4) polynomial f (x) goes through the points (−2, −33),
(−1, 3), (0, 7), (1, 15), and (2, 15). Using the points, write a system of linear equa-
tions to solve for the unknown coefficients of f (x). Use MATLAB to solve this
system and thus find the polynomial by putting the augmented matrix in RREF
form. You may use the rref command for this, but make sure that exact answers
are given.
8. Consider the following matrices:
⎡ ⎤ ⎡ ⎤
10 10 10 10 0 0 1 0
⎢ 9 8 7 6 ⎥ ⎢ ⎥
⎢ ⎥ ⎢ 0 1 0 0 ⎥
A=⎢ ⎥, B=⎢ ⎥.
⎣ 5 4 3 2 ⎦ ⎣ 1 0 0 0 ⎦
1 1 1 1 0 0 0 1
The matrix D is a special matrix in that multiplication with this matrix gives a
very specific result. Look closely at your answers for CD and DC.
(a) Multiplying on the right by D (so looking at CD) results in an elementary
operation performed on the matrix C. Which elementary operation is it?
i. SwapRows. Two rows swapped.
ii. SwapCols. Two columns swapped.
iii. MultRow. A row is multiplied by a non-zero constant.
iv. MultCol. A column is multiplied by a non-zero constant.
v. AddRow. A multiple of one row is added to another row.
vi. AddCol. A multiple of one column is added to another column.
(b) Multiplying on the left by D (so looking at DC) results in an elementary
operation performed on the matrix C. Which elementary operation is it?
i. SwapRows. Two rows are swapped.
ii. SwapCols. Two columns are swapped.
iii. MultRow. A row is multiplied by a non-zero constant.
iv. MultCol. A column is multiplied by a non-zero constant.
242 Linear Algebra Projects
13. The chemical reaction of phosphorus pentoxide and calcium fluoride into phos-
phorus pentafluoride and tricalcium phosphate:
14. The chemical reaction of aluminum and water into aluminum hydroxide and hy-
drogen:
aAl + bH2 O → cAl(OH )3 + dH2 .
Linear Algebra Projects 243
15. The chemical reaction of ammonia and oxygen into nitric oxide and water:
16. The chemical reaction hydrazine and dinitrogen tetroxide into nitrogen and water:
17. The chemical reaction of methane and oxygen into carbon dioxide and water:
18. The chemical reaction of ethane, carbon dioxide, and water into ethanol:
LINEAR ALGEBRA = 11 8 13 4 0 17 0 11 6 4 1 17 0
244 Linear Algebra Projects
Now we need to translate this new 2 × 7 matrix back into letters. This is where
MODULAR arithmetic comes in. We have used modular arithmetic without even
realizing it; translating the 24-hour clock into the 12-hour clock is arithmetic modulo
12. We may also do this when giving change to a cashier to get only quarters back.
Here is a more formal mathematical definition: Let a, b, and n be integers. We say a is
equivalent to b modulo n, denoted a ≡ b (mod n), if a − b is an integer multiple of n.
When dealing with positive integers, the easiest way to think about it is, “What is the
remainder when we divide a by n? That is b.” So for instance, when I divide 16 by 12, the
remainder is 4 so 16 ≡ 4 (mod 12). When I divide 88 by 25, I get a remainder of 13 so
88 ≡ 13 (mod 25). For modulo 26, 26 ≡ 0 (mod 26), 27 ≡ 1 (mod 26), 28 ≡ 2 (mod 26)
and so on.
THERE IS A COMMAND IN MATLAB FOR MODULAR ARITHMETIC;
THIS WILL BE USEFUL!
Thus for the matrix E above we have
20 12 25 7 24 1 23
E≡ (mod 26),
17 3 16 18 22 17 22
which then transforms into the letters URMDZQHSYWBRXW. Thus “LINEAR ALGEBRA”
gets encoded into “URMDZQHSYWBRXW”. Notice how the letter “A” is encoded
differently each time in our message.
DECRYPTION:
Obviously we would want to be able to decrypt a Hill cipher. This would involve
solving KM = E where M is unknown but E is the encoded message we are given and
K was the original encryption key matrix. Thus, if K −1 exists and we knew what it
equaled, we would get M = K −1 E. So we would want K to be an invertible matrix,
or a nonsingular one. We also want K −1 to have entries that are integers, modulo 26.
Linear Algebra Projects 245
There are other issues because of the modular arithmetic that we will not get into right
now. So how to do this?
2 3
For the above key K = , we get
1 4
−1
4
− 35
K = 5 .
− 15 2
5
We do not want fractions so what are these fractions equivalent to modulo 26? The
easiest way to show you is by example. Remember 26 ≡ 0 (mod 26) so 26
5 ≡ 5 (mod 26).
0
Thus
4 26 30
+ = =6
5 5 5
and
−3 + 26 + 26 + 26 75
= = 15.
5 5
Thus 45 ≡ 6 (mod 26) and − 35 ≡ 15 (mod 26). So you get a decryption matrix D ≡
K −1 (mod 26) and for our example,
6 15
D= .
5 16
Notice (check it!), if we would be given the encoded message E above, we get
DE ≡ M (mod 26).
TIP: If converting fractions modulo 26 by hand, write out a bunch of multiples of 26.
By writing out a bunch of multiples, I saw that 3 · 26 = 78 so if I subtracted 3, I get a
nice multiple of 5, etc.
Notice that we are not encoding numbers, spaces or punctuation—this can be done
as well by adding to our “alphabet”. For example, we could have a space = 26, “.” =
27, and “?” = 28 and we would be working modulo 29.
NOTE: Not all of the details of these commands are discussed here. Only an ex-
planation of what we need to know about the commands for our use for this project is
provided. Feel free to explore these commands further on your own!
DOUBLE
The command we need to convert our strings to ASCII codes is double. Here is an
example:
>> x='ABCD'
x =
'ABCD'
>> y=double(x)
y =
65 66 67 68
CHAR
The command to convert numbers that are ASCII codes to text is char. Here is an
example.
>> x=0:25; % creates a vector of the numbers from 0 to 25. Output is suppressed.
>> y=x+65 % adds 65 to every element in the vector so the is now from 65 to 90.
y =
Columns 1 through 18
65 66 67 68 69 70 71 72 73 74 75 76 77 78
79 80 81 82
Columns 19 through 26
83 84 85 86 87 88 89 90
>> alphabet=char(y) % alphabet is now a string that should all uppercase.
alphabet =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
RESHAPE
We want to “reshape” a vector X to a matrix of size m × n. Then we use the command
reshape(X,m,n):
1 2 3 4
>> reshape(A,2,2)
ans =
1 3
2 4
MOD
We want to see what numbers are equivalent modulo 26. The command mod(x,26)
will do this. Let us look at some examples. For example, we know from clocks that 14
is equivalent to 2 modulo 12:
>> mod(14,12)
ans =
2
We can also use the mod command if we want the last four digits of a number. Use
mod(x,10000):
>> mod(987654321,10000)
ans =
4321
For us, we want matrices modulo 26. Luckily, the command works on vectors and
matrices.
Since 30, 46, and 53 are equivalent to 4, 20, and 1, respectively, modulo 26 we see
that y now has the values 12, 4, 20, and 1.
K = [2 3;1 4];
248 Linear Algebra Projects
>> msg='LINEARALGEBRA'
msg =
'LINEARALGEBRA'
>> msgNumber=double(msg)
msgNumber =
76 73 78 69 65 82 65 76 71 69 66 82 65
Notice that msgNumber is now a vector of the ASCII codes for our message. For the
Hill Cipher we want the numbers to be from 0 to 25 instead of 65 to 90. Thus we will
subtract 65 from our msgNumber.
>> msgNumber=msgNumber-65
msgNumber =
11 8 13 4 0 17 0 11 6 4 1 17 0
Now we need to get these numbers into the correct format. Notice that there are
13 letters in this message, we want 2 rows so we would have seven columns and thus
we need one “dummy letter” of Z = 25 at the end. I could add this at the end of
my msgNumber vector (if you know how to do this) or now that I’ve figured it out, I
just redo the above commands. In your script file you would just correct the original
commands you had.
>> msg='LINEARALGEBRAZ'
msg =
'LINEARALGEBRAZ'
>> msgNumber = double(msg)-65
msgNumber =
11 8 13 4 0 17 0 11 6 4 1 17 0 25
Notice that these numbers are the same as on the handout. But from these numbers
we need to create the 2 × 7 matrix M. Thus we use the reshape command:
>> msgNumberMtx=reshape(msgNumber,2,7)
msgNumberMtx =
11 13 0 0 6 1 0
8 4 17 11 4 17 25
what each command does. You may want to suppress the output from some or all of
the intermediate steps so that you only see the end result.
>> encodedMsg=K*msgNumberMtx
encodedMsg =
46 38 51 33 24 53 75
43 29 68 44 22 69 100
>> encodedMsg=mod(encodedMsg,26)
encodedMsg =
20 12 25 7 24 1 23
17 3 16 18 22 17 22
>> encodedMsgNum=reshape(encodedMsg,1,14)
encodedMsgNum =
20 17 12 3 25 16 7 18 24 22 1 17 23 22
>> encodedMsgNum=encodedMsgNum+65
encodedMsgNum =
85 82 77 68 90 81 72 83 89 87 66 82 88 87
>> codedMsg=char(encodedMsgNum)
codedMsg =
'URMDZQHSYWBRXW'
>> D=inv(K)
D =
0.8000 -0.6000
-0.2000 0.4000
>> rats(D) % this is for display purposes only
ans =
2{\texttimes}28 char array
' 4/5 -3/5 '
' -1/5 2/5 '
Now we need to figure out what these fractions are modulo 26.
-0.2000 0.4000
>> D(1,2) + a + a + a % Re-ran this, adding "a" each time until get desired integer
ans =
15
>> D(1,2)= ans % Reassigning the 1,2 entry of D to be the previous answer
D =
6.0000 15.0000
-0.2000 0.4000
>> D(2,1)+a
ans =
5
>> D(2,1)=ans
D =
6.0000 15.0000
5.0000 0.4000
>> D(2,2)+a+a+a
ans =
16
>> D(2,2)=ans
D =
6 15
5 16
Now we have the inverse matrix, modulo 26 as in the handout. Let us check against
our encoded message. Output of the intermediate steps is suppressed.
>> codedMsg
codedMsg =
'URMDZQHSYWBRXW'
>> numCode2 = double(codedMsg);
>> numCode2=numCode2-65; % convert to numbers from 0 to 25
>> E2=reshape(numCode2,2,7) % reshape to 2x7 matrix
E2 =
20 12 25 7 24 1 23
17 3 16 18 22 17 22
Notice E2 is the same as E in the above example. Now decode and then convert to
letters:
>> chkMsg=D*E2;
>> chkMsg=mod(chkMsg,26);
>> chkMsg=reshape(chkMsg,1,14);
>> chkMsg=chkMsg+65;
>> char(chkMsg)
ans =
'LINEARALGEBRAZ'
Linear Algebra Projects 251
We may have been told that the dummy letter(s) that would be used would be Z, or
we see that the entire decoded message does not make sense as given and recognize that
the original message was “LINEAR ALGEBRA”.
C.2.2 Exercises
Complete these problems within MATLAB, showing all work, even calculations done,
within MATLAB.
1. Consider the Hill cipher with the key
2 5
.
1 4
(a) Encode the following text, adding Z if necessary, stripping spaces and punc-
tuation:
Step on no pets.
(b) Calculate the “inverse matrix” (decode matrix) with entries that are integers
from 0 to 25 (integers modulo 26).
(c) Using the decode matrix above, decode the following message, stripping off
any extraneous “dummy letters” that may have been put at the end. In other
words, strip off any extraneous “dummy letters” so that the decoded message
is an actual word or phrase in English.
SIEBZY
2. Consider the Hill cipher key in Exercise 1 above and its decode matrix.
(a) Use the key to encode “Name no one man,” adding Q if necessary, stripping
spaces and punctuation.
(b) Use the decode matrix to decode “IRGDTF” stripping off any extraneous
“dummy letters” that may have been put at the end.
3. Consider the Hill cipher with the key
1 5
.
2 7
(a) Encode the following text, adding X if necessary, stripping spaces and punc-
tuation:
Madam, I’m Adam.
(b) Calculate the “inverse matrix” (decode matrix) with entries that are integers
from 0 to 25 (integers modulo 26).
(c) Using the decode matrix above, decode the following message, stripping off
any extraneous “dummy letters” that may have been put at the end. In other
words, strip off any extraneous “dummy letters” so that the decoded message
is an actual word or phrase in English.
FYPSNE
252 Linear Algebra Projects
4. Consider the Hill cipher key in Exercise 3 above and its decode matrix.
(a) Use the key to encode “Was it a rat I saw?,” adding Q if necessary, stripping
spaces and punctuation.
(b) Use the decode matrix to decode “KUYWFN” stripping off any extraneous
“dummy letters” that may have been put at the end.
x and A
x − b = e, the “error” vector. If we make the length of e as small as possible,
we’ve minimized the error and have a “best approximation” to a solution to Ax = b.
This is what a least-squares solution is; the vector
x that makes
e = A
x − b
as small as possible.
Without getting into the details, we find the least-squares solution
x to Ax = b by
solving the system A Ax = A b.
T T
5x + 6y = 3,
6x + 7y = 1,
x + y = −5.
We see above that the system has no solutions. But the least-squares solution is the
solution to AT Ax = AT b:
x= .
24
Example C.3.2. Suppose we want a parabola (quadratic function) that best fits these
data points:
(−1, 1) (3, 0) (0, 1) (−2, −2) (2, 3)
By looking at f (x) = ax2 + bx + c we get the following equations:
f (−1) = 1 =⇒ a−b +c = 1,
f (3) = 0 =⇒ 9a + 3b +c = 0,
f (0) = 1 =⇒ c = 1,
f (−2) = −2 =⇒ 4a − 2b +c = −2,
f (2) = 3 =⇒ 4a + 2b +c = 3.
4 2 1 3
>> rref(M)
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
0 0 0 0
⎡ ⎤
− 12
⎢ ⎥
So the least-squares solution is
C.3.3 Exercises
All of the work to answer the following exercises must be done in MATLAB and appear
in your file. Even basic calculations that you would normally need scratch paper or your
calculator for should be done in MATLAB.
1. Consider the following system:
⎡ ⎤ ⎡ ⎤
2 −2 15
⎢ ⎥ ⎢ ⎥
⎣ −2 2 ⎦ x = ⎣ −9 ⎦ .
5 5 10
(a) Use MATLAB to try and solve the system and notice why we may need
least-squares.
(b) Use MATLAB to find the least-squares solution
x of the system.
Linear Algebra Projects 255
(a) Use MATLAB to try and solve the system and notice why we may need
least-squares.
(b) Use MATLAB to find the least-squares solution
x of the system.
3. Consider the linear function f (x) = mx + b with the data points (−2, 8), (0, 4), and
(2, 12).
(a) Come up with a linear system to solve for m and b.
(b) Use MATLAB to try and solve the system and notice why we may need
least-squares.
(c) Use MATLAB to find the least-squares solution
x of the system.
(d) BONUS: plot the data points and the line y = mx + b on the same figure in
MATLAB.
4. Consider the quadratic polynomial f (x) = ax2 + bx + c with the data points (0, −1),
(1, 0), (2, −7), and (3, −2).
(a) Come up with a linear system to solve for a, b, and c.
(b) Use MATLAB to try and solve the system and notice why we may need
least-squares.
(c) Use MATLAB to find the least-squares solution
x of the system.
256 Linear Algebra Projects
(d) BONUS: plot the data points and the line y = f (x) on the same figure in
MATLAB.
where one “generation” is one day. Then the value of p11 is the probability someone
in group A will stay in group A the next day, p12 is the probability someone in group
A will go to group B, p21 is the probability that someone in group B will go to group
A the next day, and finally p22 is the probability that someone in group B will stay in
group B the next day.
In this project we will look at two examples and investigate the relationship between
the Markov matrices, eigenvalues, and eigenvectors. We will also have to remember
how to calculate limits from calculus. It may be useful to remind yourself of the limit of
a geometric sequence.
There will be work shown in your MATLAB file and maybe some work on paper to
do these problems. There are examples of how to work with the characteristic function
and/or find eigenvalues on the text website.
C.4.2 Exercises
All of the work to answer the exercises below must be done in MATLAB and appear in
your file. Even basic calculations that you would normally need scratch paper or your
Linear Algebra Projects 257
The second column of A has the probabilities of being rated average at the end
of one month and then being rated the next month as poor, average and excellent,
respectively and so on. Recall that probabilities should add up to 1, that is that at the
end of any given month, the probabilities of being rated poor, average, or excellent
should add up to 1.
Find A. If you need calculations done to figure out the entries, those should be
done in MATLAB. At the minimum, the only thing needed to be done in the
MATLAB is to enter the matrix, named A.
2. Use the Markov matrix A from the previous exercise.
(a) Suppose that initially, 10% of the workers were rated poor and 75% of the
workers were rated as average. Complete the entries for the initial state vector
x0 , stating the values as percentages (thus 16 rather than 0.16 for 16%).
(b) Use MATLAB to find the percentage of workers will be rated poor after 5
months. Round your answer to two decimal places.
3. Use the Markov matrix from Exercise 1.
(a) Find the characteristic polynomial p(x) of that matrix:
(b) Given that a Markov matrix always has an eigenvalue of λ = 1, find the other 2
eigenvalues with λ2 < λ3 . USING CALCULATORS, MATHEMATICA,
MAPLE, WOLFRAM ALPHA, ETC. IS NOT ALLOWED. State the
exact values of the eigenvectors.
258 Linear Algebra Projects
4. Suppose you had the following Markov matrix instead of the one given in the
previous exercises.
⎡ ⎤
0.2 0.3 0.1
⎢ ⎥
⎣ 0.7 0.4 0.7 ⎦ .
0.1 0.3 0.2
3 1
The eigenvalues for this Markov matrix are λ1 = 1, λ2 = − , and λ3 = , with
10 10
corresponding eigenvectors
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
1 1 −1
⎢ 7 ⎥ ⎢ ⎥ ⎢ ⎥
u 1 = ⎣ 3 ⎦ , u 2 = ⎣ −2 ⎦ , u 3 = ⎣ 0 ⎦ ,
1 1 1
respectively. Notice that the matrix is NOT defective. Recall the theorem in linear
algebra that says these eigenvectors are linearly independent. Thus these vectors
form a basis for R3 so if our initial state vector was
⎡ ⎤
15
⎢ ⎥
x0 = ⎣ 75 ⎦ ,
10
we can write this initial state vector as a linear combination of the three eigenvec-
tors. In other words, we can write
x0 = a1 u1 + a2 u2 + a3 u3 .
xk = Ak (a1 u1 + a2 u2 + a3 u3 ).
Simplify the right hand side of this equation to be in terms of the coefficients
above, eigenvalues, and eigenvectors. Use the exact values for the coefficients
and eigenvalues but keep u1 , u2 , u3 in the equation.
(d) Write the resulting equation.
(e) The above equation can make calculations easier, and thus faster. Based on
this equation, use MATLAB to find the percentage that was rated as average
after 30 months, both the exact value and numerical approximation rounded
to four decimal places.
Linear Algebra Projects 259
(f) Based on the equation from the second part (with the exact values), figure
out what the lim xk equals using exact values. What is your answer rounded
k→∞
to four decimal places? (use MATLAB)
(g) Based on the meaning behind the Markov matrix and vectors x0 and xk ,
explain what this limit means for this particular application.
APPENDIX D
261
262 Multivariable Calculus Projects
t = linspace(0,2*pi);
IMPORTANT: notice the semi-colon at the end of these lines; if there is none, all
of those values for t (and x, y, etc. below) will appear in your command window. Now
we enter the equations for x and y, using component-wise calculations.
x = 3*cos(t);
y = 2*sin(t);
plot(x,y)
title('2D Vector Function Example 1')
The above equations did not need component-wise calculations. This example
sin(2t) cos(2t)
does: r(t) = ,
4 + t2 4 + t2
t = linspace(0,10);
x = sin(2*t)./(4 + t.^2);
y = cos(2*t)./(4 + t.^2);
plot(x,y)
title('2D Vector Function Example 2')
t=linspace(0,4*pi);
x=(2+cos(1.5*t)).*cos(t);
y=(2+cos(1.5*t)).*sin(t);
z=sin(1.5*t);
plot3(x,y,z)
xlabel('x'), ylabel('y'), zlabel('z')
title('3D Vector Function/Space Curve Example')
Multivariable Calculus Projects 263
t=linspace(0,4*pi);
x=cos(6*t);
y=sin(6*t);
z=t;
plot3(x,y,z)
xlabel('x'), ylabel('y'), zlabel('z')
title('Bad Domain Example')
The problem above was because by default the linspace(a,b) command creates
one hundred values between a and b for MATLAB use to connect to plot the graph.
By having linspace(a,b,n), you are specifying n values between a and b. So below,
we have t equal a vector of 500 values between 0 and 4π with which to create the x, y,
and z values to build points to connect into a graph.
t=linspace(0,4*pi,500);
x=cos(6*t);
y=sin(6*t);
z=t;
plot3(x,y,z)
xlabel('x'), ylabel('y'), zlabel('z')
title('Better Domain Example')
t=linspace(0,4*pi);
x=(2+cos(1.5*t)).*cos(t);
y=(2+cos(1.5*t)).*sin(t);
z=sin(1.5*t);
plot3(x,y,z)
view(0,90)
xlabel('x'), ylabel('y'), zlabel('z')
title('Adjusting View on 3D Graph')
[x,y,z]=sphere(100);
mesh(x,y,z)
xlabel('x'), ylabel('y'), zlabel('z')
title('Sphere Command: Unit Sphere')
axis equal
axis([-5 5 -5 5 -5 5])
[x,y,z]=sphere(100);
mesh(3*x,3*y,3*z)
xlabel('x'), ylabel('y'), zlabel('z')
title('Sphere with different radius')
axis equal
axis([-5 5 -5 5 -5 5])
How to get a sphere with a different center C (2, −1, 3) from the origin:
[x,y,z]=sphere(100);
mesh(x+2,y-1,z+3)
xlabel('x'), ylabel('y'), zlabel('z')
title('Sphere with center not at the origin')
axis equal
axis([-5 5 -5 5 -5 5])
QUESTION: How could you get ANY sphere; a different center from the origin
and radius other than 1?
Here they are side-by-side for comparison:
subplot(131)
mesh(x,y,z)
xlabel('x'), ylabel('y'), zlabel('z')
title('Sphere Command: Unit Sphere')
axis equal
axis([-5 5 -5 5 -5 5])
subplot(132)
mesh(3*x,3*y,3*z)
xlabel('x'), ylabel('y'), zlabel('z')
title('Sphere with different radius')
axis equal
axis([-5 5 -5 5 -5 5])
subplot(133)
mesh(x+2,y-1,z+3)
xlabel('x'), ylabel('y'), zlabel('z')
title('Sphere with center not at the origin')
axis equal
axis([-5 5 -5 5 -5 5])
Multivariable Calculus Projects 265
t = linspace(-pi,3*pi);
x = 2*cos(t);
y = sin(t);
z = t;
plot3(x,y,z, 'k')
xlabel('x'), ylabel('y'), zlabel('z')
title('Multiple Graphs in One Example')
hold on % use this to add more plots to current figure
t2 = linspace(-1,1);
x2=-2*t2;
y2=1 + 0*t2;
z2=pi/2 + t2;
plot3(x2,y2,z2)
hold off % make sure you have this at the end
D.2.7 Exercises
1. Consider the vector function with parametric equations
x = cos(t) 4 − 0.25 cos2(10t) + 5,
y = sin(t) 4 − 0.25 cos2(10t) + 9,
z = 0.5 cos(10t) − 8.
(a) Show that, for any t, the space curve from these parametric equations lies on
a sphere by finding the equation of the sphere, showing all work on paper.
Hint: using these equations for x, y, and z, can you get something in the
form of (x − h)2 + (y − k)2 + (z − l)2 = r 2 ? Write the equation of the sphere.
What is the center and radius of the sphere?
(b) Within MATLAB, plot the parametric equations to make the space curve.
Make sure your domain is defined nicely so you get the entire graph and it is
not a jagged curve.
(c) Within MATLAB, create a second plot of the space curve and the sphere
(using the sphere command) so they appear in the same figure. Make the
space curve black and thicker than the default.
2. Consider the vector function with parametric equations
x = cos(π t),
y = sin(π t),
266 Multivariable Calculus Projects
z = 3 sin(π t).
(a) Find the vector form of the equation of the tangent line to the curve at t = 1.
(b) Find the vector form of the equation of the tangent line to the curve at
t = 1/2.
(c) Find the point of intersection of these two lines.
(d) Within MATLAB, plot the parametric equations, the tangent lines and the
point. Make sure your domain is defined nicely so you get the entire graph
and it is not a jagged space curve. Make the space curve in black, the first
tangent line in blue, the second in red, and mark the point of intersection
with a black x.
3. Consider the surface f (x, y) = 4x2 y + 15 + 2xe1−y ln(x).
(a) Find the equation of the tangent plane to when x = 1 and y = 1. Show your
work on paper.
(b) Within MATLAB, graph the surface z = f (x, y) and the tangent plane, mark-
ing the point (1, 1, f (1, 1)). Make the surface yellow, the tangent plane or-
ange, and the point black. Make the domain for x to be from 0.000001 to 3
and the domain for y from 0 to 3.
BONUS: Use the AnimateView2 function found on the text website to cre-
ate an animated gif picture.
(c) Notice that the above question could have been phrased “find the linear
approximation L (x, y) of the function f (x, y) = ... at ...” and the answer would
have been the same.
Use your answer above to approximate f (1.01, 0.99) by calculating this
approximation within MATLAB. Name the approximation calculation
fApprox within MATLAB.
(d) Have MATLAB calculate the actual value of f (1.01, 0.99) (answer given to
four decimal places by default). Name this calculation of f fActual within
MATLAB.
>> syms x y
>> int1 = int(x^2 + y^2, y, 0, 1)
int1 =
Multivariable Calculus Projects 267
x^2 + 1/3
>> int2 = int(int1, x, -2, 2)
int2 =
20/3
x=linspace(0,2.5);
y=5-2*x;
fill([x,0],[y,0], [0.75, 0.75, 0.75])
axis([0,2.5,0,5.5]) % adjust the axis([xmin, xmax, ymin, ymax]) if necessary
title('Projection of Tetrahedron onto xy-plane')
D.3.2 Exercises
Use MATLAB to calculate the integrals needed to answer the following questions. Show
all work on paper any calculations needed to set them up. Sketch the regions involved.
1. Find the mass and center of mass of the lamina that occupies the region D bounded
√
by the parabolas y = 81 x and x = 9y2 and has density function ρ(x, y) = x. Plot
1 2
(a) Use MATLAB to graph the bumpy sphere using spherical coordinates and
then converting to rectangular coordinates to get x, y, z defined. This can
be done by setting up the proper domains for θ and φ using meshgrid,
calculating ρ and then creating x, y, and z using the sph2cart command.
Use mesh, making the EdgeColor the color of your choice.
(b) Write on paper the integral that would be used to calculate the volume of
this bumpy sphere.
(c) Use MATLAB to calculate the exact value of the volume of the bumpy
sphere.
(d) Write the answer MATLAB gives for the volume on paper, writing it in cor-
rect notation.
√
For example, if MATLAB gives the answer as pi∗sqrt(3)/2,
write π 2 3 .
6. Consider the integral f (x, y, z)dV where E is the solid bounded by z = 0, x =
E
0, z = y − 8x and y = 24.
(a) Use MATLAB to draw the 3D solid.
(b) It may be helpful to sketch on paper the projections of the solid onto the
2D coordinate planes to help change the order of the iterated integrals. You
can get help for these sketches by adjusting the view of the 3D solid within
MATLAB.
(c) Express the integral f (x, y, z)dV as an iterated integral in six different
E
ways, where E is the solid bounded by z = 0, x = 0, z = y − 8x and y = 24.
(d) Choose one of the above six iterated integrals to have MATLAB compute
if f (x, y, z) = xyz using the Symbolic Math Toolbox. Which one did you
choose and what is the answer?
References
[1] Stormy Attaway, MATLAB: A Practical Introduction to Programming and Problem Solving, third
edition, Elsevier: Butterworth-Heinemann, Amsterdam, 2013.
[2] Michael Barnsley, Fractals Everywhere, second edition, Morgan Kaufmann, 2000.
[3] Niraj Chokshi, How Powerball manipulated the odds to create a $1.5 billion jackpot, Washington
Post, January 13, 2016, https://www.washingtonpost.com/news/post-nation/wp/2016/01/13/how-
powerball-manipulated-the-odds-to-make-a-1-5-billion-jackpot-happen/.
[4] Robert L. Devaney, The Chaos Game, http://math.bu.edu/DYSYS/chaos-game/node1.html, 1995.
[5] Educational Testing Service, GRE graduate record examinations guide to the use of scores, http://
www.ets.org/gre/guide, 2019.
[6] Temple H. Fay, The butterfly curve, The American Mathematical Monthly 96 (5) (1989) 442–443,
https://doi.org/10.2307/2325155.
[7] C.D. Fryar, Q. Gu, C.L. Ogden, K.M. Flegal, Anthropometric reference data for children and adults:
United States, 2011–2014, National Center for Health Statistics, Vital Health Statistics 3 (39) (2016),
https://www.cdc.gov/nchs/data/series/sr_03/sr03_039.pdf.
[8] Golden Gate Bridge Highway & Transportation District, FAQ, https://www.goldengate.org/faq/#59.
[9] Golden Gate Bridge Highway & Transportation District, School Projects, https://www.goldengate.
org/bridge/history-research/educational-resources/school-projects/, 2006–2018.
[10] Lester S. Hill, Cryptography in an algebraic alphabet, The American Mathematical Monthly 36 (6)
(Jun. - Jul. 1929) 306–312.
[11] Lester S. Hill, Concerning certain linear transformation apparatus of cryptography, The American
Mathematical Monthly 38 (3) (Mar. 1931) 135–154.
[12] Guinness World Records Limited, Fastest Lacrosse Shot, https://www.guinnessworldrecords.com/
world-records/fastest-lacrosse-shot?fb_comment_id=605553549549656_647775638660780, 2019.
[13] Desmond J. Higham, Nicholas J. Higham, MATLAB Guide, second edition, Society for Industrial
and Applied Mathematics, Philadelphia, 2005.
[14] Ben Joffe, Functions 3D: examples, https://www.benjoffe.com/code/tools/functions3d/examples,
2019.
[15] Lee W. Johnson, R. Dean Riess, Jimmy T. Arnold, Introduction to Linear Algebra, fifth edition,
Addison-Wesley, Boston, 2002.
[16] Benoit B. Mandelbrot, The Fractal Geometry of Nature, 1983.
[17] The MathWorks, Inc., MATLAB Documentation, https://www.mathworks.com/help/matlab/,
2019.
[18] Todd Neller, The Game of Pig, Gettysburg College Department of Computer Science, http://cs.
gettysburg.edu/projects/pig/piggame.html. (Accessed 30 September 2019).
[19] David Nicholls, Fractal ferns, https://www.dcnicholls.com/byzantium/ferns/fractal.html, 1998.
[20] Robert Osserman, Mathematics of the Gateway Arch, Notices of the American Mathematical Society
57 (2) (February 2010) 220–229.
[21] Rapid Tables, CMYK to RGB color conversion, https://www.rapidtables.com/convert/color/cmyk-
to-rgb.html.
[22] SPACE.com Staff, What Is the Distance Between Earth and Mars?, Future US, Inc., https://www.
space.com/14729-spacekids-distance-earth-mars.html, March 1, 2012.
[23] E.M. Standish, Keplerian Elements for Approximate Positions of the Major Planets, Solar System
Dynamics Group, JPL/Caltech, https://ssd.jpl.nasa.gov/txt/aprx_pos_planets.pdf.
[24] James Stewart, Single Variable Calculus: Early Transcendentals, eighth edition, Cengage Learning,
Boston, MA, USA, 2016.
271
272 References
[25] James Stewart, Multivariable Calculus: Early Transcendentals, eighth edition, Cengage Learning,
Boston, MA, USA, 2016.
[26] J.D. Watson, F.H. Crick, Molecular structure of nucleic acids; a structure for deoxyribose nucleic acid,
Nature 171 (4356) (April 1953) 737–738.
[27] Gareth Williams, Linear Algebra with Applications, seventh edition, Jones & Bartlett Publishing, 2009.
Index
A D
Alternating series, 167, 168, 172, 178, 179, 181 Default
Angle, 31, 68, 77, 135, 136, 138, 139, 143, 149, colormap, 68
151, 156 colors, 42, 44, 45, 146, 158, 159
Approximating quadratic, 186–188, 191 LineWidth, 43
ASCII files, 11 MarkerSize, 43
Augmented matrix, 201 view, 69
Axes, 36, 38, 39, 53, 54, 57, 79, 81, 142, 144, 190, width, 52
212 Deleting elements, 20
Azimuth angle, 77 Dice rolls in MATLAB® , 55
Differentiable functions, 194
DNA helix, 79
B Domain, 33, 34, 52, 53, 59, 62, 63, 65, 72, 78–81,
Barnsley fern, 144 108, 141, 183, 191, 194, 213
Barnsley fern fractal, 140 definitions, 34
Batch files, 11 issues, 64
Butterfly curve, 56 Double helix, 78
C E
Catenary curve, 52 Eager versions, 94, 95
Chaos game, 153, 158–160 Ellipse, 36, 37, 135, 141–143
Characteristic functions, 99–101 Equilateral triangle, 153, 154, 158, 161
Code, 33, 45, 48, 55, 65, 66, 68, 74, 91, 101–103, Error, 103, 107, 108, 112, 144, 158, 159, 176, 178,
111, 122, 124, 129, 131, 145, 161, 163, 179, 189, 190
165, 212 bounds, 185, 186
improvement, 129, 130 checking, 90, 92, 109, 189
RGB, 45, 141 checks, 91, 92, 108, 110, 144, 189, 191, 211
vectorization, 130 estimate, 188
Colon operator, 29, 34, 65, 100, 101 message, 104, 107–110, 113, 117, 161, 162, 164,
Color, 33, 43–45, 54, 59, 66, 81, 106, 107, 119, 177–181, 189, 190, 211
141, 142, 144, 146, 153, 158, 159, 189, tolerance, 178, 179
212 Euclidean vector spaces, 139, 193
Colormap, 68 Exponential function, 174
Command
alpha, 122 F
window, 3, 4, 7, 10, 11, 60, 85, 111, 119, 211, Fern, 146
212 fractal, 140, 144–146
Conditionally convergent, 168 File format, 84
Contour plot, 65, 81 File function, 85, 104, 158, 159
Convergent geometric series, 170 Fill command, 119
Curve, 33, 40, 49, 50, 52–54, 56, 80, 119, 120, Format, 4, 8, 9, 13, 14, 17, 84, 102, 115, 116, 118
165, 183, 186–188, 191 Fprintf command, 115
Cylinder, 74, 81 Fractal snowflake, 162
273
274 Index