Matlab
Matlab
William Bober
MATLAB ® is a trademark of The MathWorks, Inc. and is used with permission. The MathWorks does not
warrant the accuracy of the text or exercises in this book. This book’s use or discussion of MATLAB® software
or related products does not constitute endorsement or sponsorship by The MathWorks of a particular
pedagogical approach or particular use of the MATLAB ® software.
CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742
This book contains information obtained from authentic and highly regarded sources. Reasonable efforts
have been made to publish reliable data and information, but the author and publisher cannot assume
responsibility for the validity of all materials or the consequences of their use. The authors and publishers
have attempted to trace the copyright holders of all material reproduced in this publication and apologize to
copyright holders if permission to publish in this form has not been obtained. If any copyright material has
not been acknowledged please write and let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmit-
ted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented,
including photocopying, microfilming, and recording, or in any information storage or retrieval system,
without written permission from the publishers.
For permission to photocopy or use material electronically from this work, please access www.copyright.
com (http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood
Drive, Danvers, MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides licenses and
registration for a variety of users. For organizations that have been granted a photocopy license by the CCC,
a separate system of payment has been arranged.
Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used
only for identification and explanation without intent to infringe.
Visit the Taylor & Francis Web site at
http://www.taylorandfrancis.com
Preface ......................................................................................................................ix
Acknowledgments .............................................................................................. xiii
Author .....................................................................................................................xv
v
vi Contents
Before MATLAB, it was rare that I would write a computer program without
using a for loop. With that in mind, in this textbook, I introduce for loops
as early as is feasible. The authors of most other MATLAB textbooks intro-
duce for loops at a much later stage in their books.
Although students at FAU take the computer programming course in their
sophomore year, having taken Calculus II, the textbook can also be used at
the freshman level (the first eight chapters do not involve calculus). Although
there are many engineering example applications, the governing equations
are given without derivations. Therefore, students not only see variables x and
y but also see variables of pressure (p), temperature (T), time (t), velocity (V),
ix
x Preface
voltage (v), current (i), and so on. The chapters include review sections,
which may be used by the course instructor to ask the class questions on the
material that has been recently covered.
The primary objectives of the textbook are as follows:
I have tried to organize the material so that the student gets to write a mean-
ingful program within several weeks of starting the course. The students
are required to add a comment section to their programs describing what
the program is about. Nearly all exercises and projects require the student to
produce tables or graphs or both.
The text contains many complete sample MATLAB programs and their
results, including tables, graphs, and comments what the program is about.
These examples should provide guidance to the student on completing the
exercises and projects that are listed in each chapter. Projects are at the end
of the chapters and are usually more difficult than the exercises. Many of
the projects are nontrivial. In recent times, I have used several exercise prob-
lems as in-class exams in which students submit their MATLAB programs
and results to me on blackboard. Projects are given as take-home exams to
be submitted to me within 1 or 2 weeks, depending on the difficulty of the
project. The projects require the student to write a computer program in
MATLAB to solve a mathematical or engineering-type problem.
The computer applications course that I teach is run as a lecture-laboratory
course. The advantage of running the course in this manner is that the
instructor is in the computer laboratory to help the student debug his or her
program. This includes the example programs as well as the exercises and
the projects. See the Table of Contents to get a more complete description of
the material covered in this textbook.
Preface xi
All example scripts in this book are available for download on the CRC
Press Website at https://www.crcpress.com/MATLAB-Essentials-A-First-
Course-for-Engineers-and-Scientists/Bober/p/book/9781138032378 .
I thank Jonathan Plant of CRC Press for his confidence and encouragement in
writing this textbook. I thank Dr. Andrew Stevens for allowing me to extract
many electrical engineering concepts and projects from our joint textbook
titled Numerical and Analytical Methods with MATLAB for Electrical Engineers.
I also thank Ed Curtis and Bala Gowri for guiding me through the textbook
submission process. I also thank the following people for their graphic con-
tributions: Danielle Mitchell and Jacqueline Ferrer. Finally, I wish to express
my deep gratitude to my wife for tolerating the many hours I spent on prepa-
ration of this manuscript—time which otherwise would have been devoted
to my family.
xiii
Author
xv
1
Computer Programming with MATLAB®
for Engineers
1.1 Introduction
Most, if not all, engineering companies use computers in one way or the
other. Many employ computer programmers to solve company-specific
problems. These companies may also purchase or license software pack-
ages such as C/C++ or MATLAB®, and install the programs on their
computer systems to enable their programmers and engineers to efficiently
solve company-specific problems. The field of engineering, in particular,
lends itself to analytical and numerical solutions due to the highly math-
ematical nature of the field. Analytical and numerical methods invariably
involve writing computer code to solve a problem of interest. Mathematical
methods for solving many types of engineering problems use concepts from
linear algebra, root extraction of polynomial and transcendental equations,
integration, curve fitting, differential equations, and so on. MATLAB, using
a variety of analytical and numerical methods, has created built-in functions
that enable the user to readily employ these mathematical methods.
However, the user needs to know some programming techniques to effec-
tively make use of these built-in functions. Many examples involving the
use of these built-in functions are covered in this textbook.
1
2 MATLAB® Essentials
This textbook is mostly concerned with item 1, that is, solving mathematical
models of physical phenomena.
The engineer’s interest lies in
MATLAB borrows many constructs from other languages. For example, the
for and while loops and the fprintf commands are from the C program-
ming language (or its descendents C++). However, the biggest difference is
that the basic element in MATLAB is a matrix, thus providing the ability to
manipulate large amounts of data with a terse syntax, and allowing for the
solution of complicated problems in just a few lines of code. In addition,
MATLAB is also very rich in presentation functions to display sophisticated
plots and graphs.
then run the example programs on their own computer and see the results. It
may also be beneficial for students to type-in a few of the sample programs
(along with some inevitable syntax and typographical errors), thereby giving
the student the opportunity to see how MATLAB responds to program errors
and subsequently learn what they need to do to fix the problem.
REVIEW 1.1
1. List several ways engineers use the computer.
2. List several areas of interest for engineers.
3. List several methods that can be used in the design of new
products.
4. Which method mentioned in item 3 is the least expensive?
5. List several components of a typical desktop/laptop computer
system.
6. Name several computer languages used today and in the past
by Engineers.
7. What is the lowest level computer language and what number-
ing system does it use?
8. For engineers, what is the principle advantage of using MATLAB
over several of the other computer programming languages?
9. List several recommendations in developing a computer
program for solving a particular problem.
10. List several building blocks available in developing a program
in MATLAB or in most other Engineering Software Platforms
such as C or C++.
2
MATLAB® Fundamentals
2.1 Introduction
MATLAB® is a software program for numeric computation, data analysis,
and graphics. One advantage that MATLAB has for engineers over program-
ming languages such as C or C++ is that the MATLAB program includes
functions that numerically solve
9
10 MATLAB® Essentials
4. Loop statements.
5. Conditional Operators (leading to alternate paths in the program).
6. Functions (built-in and self-written).
Items (1)–(4) are covered in this chapter as well as some of the elementary
built-in functions of item (6). Items (5) and (6) are covered in Chapter 3.
Examples of MATLAB programs that solve various types of mathematical
problems, many of which are related to engineering-type problems, are
covered throughout this book.
FIGURE 2.1
MATLAB desktop windows for the three-column option.
the entire script must be retyped. By using the up arrow (↑) key
on your keyboard, the previous command can be retrieved (and
edited) for reexecution.
• Current folder toolbar: This Toolbar gives the path to the Current
Folder. To run a MATLAB script, the script needs to be in the folder listed
in this Toolbar.
• Current Folder Window (on the left): This window lists all the files in
the Current Folder whose path is listed in the Current Folder Toolbar.
By double clicking on a file in this window, the file will open within
MATLAB.
• Workspace Window: This window will be on the right for a three-
column option (see Figure 2.1) or below the Current Folder Window
for the two-column option (see Figure 2.2). The two- or three-column
option can be selected from the layout options in the Toolstrip.
The Workspace Window contains all the commands entered into
the Command Window.
• Editor Window: To open this window, click on the New Script icon
in the Toolstrip in MATLAB’s desktop (see Figure 2.1). This will
open the Editor Window (see Figure 2.3). This window may be used
to create, edit, and execute MATLAB scripts (also called programs).
Figure 2.4 contains the script for Example 2.1.
12 MATLAB® Essentials
FIGURE 2.2
MATLAB desktop windows for two-column option.
FIGURE 2.3
Editor Window just above the Command Window.
MATLAB® Fundamentals 13
FIGURE 2.4
Script for Example 2.1.
4. When you are finished typing in the program, save the script by click-
ing on the Save icon in the Toolstrip (see Figure 2.3). A dialog box will
open in which you are to select the folder (left column), and in which
you are to type-in the name of the script in the File Name Dialog
Box (see Figure 2.5). By default, your program will be saved with the
.m extension. It is best to use a folder that contains only your own
MATLAB scripts.
5. You may then run the script in the Editor Window by clicking on the
arrow located just above the Run icon in the Toolstrip (see Figure 2.6).
This icon is a Save and Run Command. Note: In the Editor Window,
the arrow is green.
Alternatively, you can run the script from the Command Window
by typing the script name (without the .m extension) after the MATLAB
prompt (>>). For example, if the program has been saved as heat.m,
then type heat after the MATLAB prompt (>>), as shown below:
>> heat
FIGURE 2.5
Select folder (left column) and type in the name of the script in the file name dialog box.
MATLAB® Fundamentals 15
FIGURE 2.6
Save and Run icon in the toolstrip.
6. If you try to run your script and your script is not in the Current
Folder whose path is listed in the Current Folder Toolbar, a dialog
box will appear giving you the option of changing the folder listed
in the Current Folder Toolbar to the folder containing your script
(see Figure 2.7). If a path to the folder containing the script has
already been established, click on the Change Folder button.
7. If you need additional help on getting started, you can click on the
Help icon in the Toolstrip in MATLAB’s desktop (see Figure 2.2).
If you are in the Editor Window, click on Home (upper left) to
get back to MATLAB’s desktop. In the window that opens (see
Figure 2.8) you can type-in an item of interest in the search box, or
you can click on the MATLAB option that brings up the window
shown in Figure 2.9.
8. Whenever you write a script, it is good practice to add comment lines
at the beginning of the script describing what the program is about.
This is accomplished by placing a % sign in front of a statement in the
script. Example:
FIGURE 2.7
Dialog box for changing folder or path.
FIGURE 2.8
Help window.
MATLAB® Fundamentals 17
FIGURE 2.9
Topics in the MATLAB Help window.
REVIEW 2.1
1. What are the two alternative ways to start the MATLAB
program?
2. What are the windows in the MATLAB’s default desktop?
3. It is best to write a MATLAB script (program) in the Editor
Window. From MATLAB’s default desktop, how does one
open the Editor Window?
4. After you have completed writing a script in the appropriate
window, what is the next step?
5. Name two ways to execute a script.
6. What happens if you try to run a script and the folder contain-
ing the script is not listed in the Current Folder Toolbar?
7. In MATLAB, what is the file name extension for saved scripts?
8. How does one establish a comment line in a script?
18 MATLAB® Essentials
1 3
A=
6 5
A scalar has just one value in the computer memory, whereas a vector of n
elements will have n values in the computer memory, and a matrix of n rows
and m columns will have n × m values in the computer memory.
To make it easier to follow ones program, it is best to use variable names that are
similar to the variables used in a problem statement.
MATLAB command names and variable names are case sensitive.
Numerical variables can be either an integer (no decimal point) or a float-
ing point number (one with a decimal point). Integers can be stored in either
8 bits (numbers less than 127 or greater than −127), 32 bits (numbers less
than 32,767 or greater than −32,767) or 64 bits of memory. In MATLAB, the
default for floating point numbers is double precision that requires 64 bits of
memory. You can specify variables to be single precision that only requires
32 bits of memory. Calculations carried out in single precision are faster than
carrying out calculations in double precision. For all problems in this text-
book, time of execution is not a problem. Numbers larger than approximately
3.4 × 10 38 or less than − 3.4 × 10 38 requires double precision.
When defining a variable, either in the Command Window or in a script,
you should place a semicolon after the variable definition when you do not
want the command echoed to the screen. In the absence of a semicolon,
the defined variable appears on the screen. For example, if you entered the
following command in the Command Window:
>> A = [3 4 7 6]
A =
3 4 7 6
>>
MATLAB® Fundamentals 19
Alternatively, if you add the semicolon after the command statement, then
your command is entered but there is nothing printed to the screen, and the
prompt immediately appears for you to enter your next command:
>> A = [3 4 7 6];
>>
x=10; y=20;
x=x+y;
What the computer does is to determines the value of x+y, which equals
30, and replaces the original value of x, which is 10, with the new value
of 30. Although, algebraically, the expression x=x+y does not make sense,
since that would make y=0, it does make sense in programming language.
Although, algebraically you can write x+y=20, you cannot do this in the
programming language. There needs to be a single variable on the left-hand
side of the = sign.
You may have noticed that in the variable assignments above that we placed
a semicolon at the end of the assignment. This avoided the variables from
being echoed to the screen.
20 MATLAB® Essentials
+ Addition
− Subtraction
* Multiplication
/ Division
^ Exponentiation
clc;
c = 36.0; m = 3.0;
y = c/2*m
This would give the wrong answer for y. MATLAB would divide c by 2
and multiply the result by m. The correct ways to write the expression are
y = c/(2*m) or c/2/m
In the first expression, MATLAB will first carry out the expression within
the parentheses, so that the 2*m becomes one number, and then c is divided
by this one number. In the second expression, there are no parentheses, so
MATLAB, proceeding from left to right, will calculate c/2, then divide the
result by m. Try typing these expressions in the Command Window and
observe the two different answers you get for y.
To display a variable value, just type the variable name without the
semicolon, and the variable will appear on the screen.
Try typing these commands into the Command Window and verify the
results:
MATLAB® Fundamentals 21
clc;
x = 5; y = 10; z = x + y <enter>
w = x – y <enter>
z = y/x <enter>
z = x*y <enter>
u = x^2 <enter>
where the semicolon within the brackets indicates the start of a new row
within the matrix. In the above expression for matrix A, row 1 are the elements
1 and 3, row 2 are the elements 6 and 5, column 1 are the elements 1 and 6, and
column 2 are the elements 3 and 5.
A matrix of 1 row and 1 column is a scalar. Example:
>> A = [ 3.5 ];
gives b = 1.5 .
1 3
If A = , then
6 5
>> b = A(2,2)
gives b = 5.
You can also define a vector by specifying each element in the vector, for
example:
MATLAB has a built-in value for the variable π. Its symbol is pi, and it should
be used in place of 3.14 whenever π appears in an arithmetic statement.
Typing pi in the Command Window gives
>> pi
ans =
3.1416
>>
The display default is four places, but it is carried to many more places in
memory.
If you had an expression in which you accidentally divided by zero, MATLAB
would respond with the infinity value, ∞, with the symbol, inf. Example:
sin( ) sine
cos( ) cosine
tan( ) tangent
clc;
x = 50/180*pi; y = sin(x) <enter>
z = cos(pi/2) <enter>
The answer should be 0, but with round off error it gives 6.1232e-17.
w = tan(pi/4) <enter>
x = 45/180*pi; y2 = sin(x) <enter>
z2 = cos(x) <enter>
x1 = sind(50) <enter>
y1 = cosd(90) <enter>
w1 = tand(45) <enter>
Since the values of the sine and cosine functions vary from −1 to +1. The input
arguments to the asin( ) and acos( ) functions should be from −1 to +1.
The results will be in radians. The value of the tan function can be anywhere
from (−∞ to + ∞ ), so the input argument to the atan( ) function can be any
number, but the result will be in radians.
MATLAB® Fundamentals 25
Try typing these statements into the Command Window and use your
calculator to verify the results:
clc;
x = asin(0.5); xd = x*180/pi <enter>
y = acosd(-1.0) <enter>
z = atand(1.732) <enter>
z = atan(1.0); zd = z*180/pi <enter>
Try typing these statements into the Command Window and use your
calculator to verify the results:
clc;
x = 2.5; y = exp(x) <enter>
z = log(y) <enter>
w = sqrt(x) <enter>
u = log10(100) <enter>
k 2
c
y = cos − t
m 2m
k = 200; c = 5; m = 25; t = 5;
arg = sqrt(k/m - (c/(2*m))^2);
y = cos(arg*t )
26 MATLAB® Essentials
z = x + yj;
The x part is considered the real part of the complex number and the y part
is considered as the imaginary part of the complex number.
The complex number can also be expressed in polar form, for example:
z = r * exp(j*theta).
MATLAB allows the use of i and j for −1. Programmers who have expe-
rience with FORTRAN, the programming language that was commonly
used in engineering many years ago, frequently used i and j as integer loop
variables.
In this book we do not deal with complex numbers very often, but when
we do, we will use j for −1. Also, there are many examples in this book
where i is used as an integer loop variable.
Try typing these statements into the Command Window and use your calcu-
lator to verify the results:
clc;
z1 = 1 + j; z2 = 2*exp(j*pi/6)=2*(cos(pi/6)+j sin(pi/6));
y = abs(z1) <enter>
w = real(z2) <enter>
v = imag(z2) <enter>
size(X) Gives the size (number of rows and the number of columns of
matrix X).
x' Transposes a matrix or vector, rows become columns and
columns become rows.
length(X) For vectors, length(X) gives the number of elements in X.
(Continued)
MATLAB® Fundamentals 27
NO T E : The repeat of A is not necessary, but it will make it easy to see the
results of n, y, z, w, and u.
clc;
A = [ 2 15 6 18 ]; n = length(A) <enter>
A <enter> y = max(A) <enter>
A <enter> z = sum(A) <enter>
A <enter> w = mean(A) <enter>
A <enter> u = sort(A) <enter>
A = [ 2 15 6 18; 15 10 8 4; 10 6 2 3 ]; <enter>
A' <enter>
A <enter> x = max(A) <enter>
A <enter> y = sum(A) <enter>
A <enter> w = mean(A) <enter>
A <enter> u = sort(A) <enter>
A <enter> z = size(A) <enter>
w = mod(21,2) <enter>
u = mod(20,2) <enter>
5 7 10
if A = 2 5 2
1 3 1
5
then x = A(:,1) gives x = 2
1
The colon in the expression A(:,1) implies all the rows in matrix A,
and 1 implies column 1.
7 10
x = A(:,2:3) gives x = 5 2
3 1
The first colon in the expression A(:,2:3) implies all the rows in A,
and the 2:3 implies columns 2 and 3.
We can also write
The 1 implies the first row and the colon implies all the columns.
2. Colon operator can also be used to generate a series of numbers
(as in a for loop, which is discussed later) or to create a vector.
The format is
n = starting value: step size: final value.
If the step size is omitted, the default step size is one. Example:
n = 1:8 gives n = 1 2 3 4 5 6 7 8 .
To increment in steps of 2 use
n = 1:2:7 gives n = 1 3 5 7
Exercise
E2.1. Type the following matrix in the Command Window. Assume that the
first, second, and third columns represent the vector variables of altitude,
z, temperature, T, and density, rho respectively: (a) use the colon operator
MATLAB® Fundamentals 29
to define the vector variables, (b) determine the mean values of altitude,
temperature, and density, (c) determine the length of vector z, and (d)
determine the size of matrix A. Print the results to the Command Window.
0 288.15 1.2252
1000 281.65 1.1118
2000 275.15 1.0065
A=
3000 268.65 0.9091
4000 262.15 0.8191
5000 255.65 0.7360
0 0 0
A = zeros(3) = 0 0 0 (3 rows, 3 columns)
0 0 0
0 0
B = zeros(3:2) = 0 0 (3 rows, 2 columns)
0 0
REVIEW 2.2
1. List at least two conditions in selecting a name for a variable.
2. Finish the following statement. An arithmetic statement may
involve …
3. What can be said about the variables that appear on the right
side of an arithmetic statement?
4. List the Arithmetic Operators in MATLAB.
5. What is the order in which an arithmetic statement will be
carried out?
(Continued)
30 MATLAB® Essentials
>> X = [0 1 2 3 4 5];
>>
>> X
X =
0 1 2 3 4 5
>>
MATLAB® Fundamentals 31
0 1 2 3 4 5
m/s
>>
The \n in the above command tells MATLAB to move the cursor to the
next line.
MATLAB also has a tab command. It is \t; this command tells MATLAB
to move the cursor several spaces along the same line.
The %f refers to a formatted floating point number that is assigned to vari-
able V, and the default is 6 decimal places. The command fprintf uses
format strings based on the C programming language. You can specify the
number of spaces allotted for the printed variable as well as the number of
decimal places by using %8.2f. This will allow eight spaces for the variable
to two decimal places. You can also just specify the number of decimal places
for the variable and let MATLAB decide the number of spaces allotted for the
printed variable. For example, to specify three decimal places use %.3f. The
variable will be printed out to three decimal places, but MATLAB will decide
the number of spaces for the variable. However, to create neat looking tables,
it is best to specify the number of spaces in the format statement that allows
for several spaces between variables in adjacent columns, such as %10.3f.
32 MATLAB® Essentials
Other formats:
fo = fopen('filename','w')
Thus, fo is a pointer to the file named filename, and the w indicates that
there will be writing to the file. The fo can be replaced by a name selected
by the programmer. To print to filename use
fprintf(fo,'format',var1,var2,..);
where the format string contains the text format for var1, var2, and so on.
Try typing the following example script in the Editor Window, save the
script in the folder that you have chosen for your MATLAB scripts (this
becomes the current folder), then run the script (see Section 2.3). The output
should go to the file named output.txt, which should be located in the same
folder as the script that produced it. To see the results, open the output file,
as described below. If you wish, you can edit the results and also print the
results by clicking on the print command in the Toolstrip.
Example 2.1
% Example_2_1.m
% This program is an example for printing to a file.
clear; clc;
V=12; % velocity
F=50.2; % force
fo=fopen('output.txt','w');
fprintf(fo,'V=%4i m/s, F = %5.2f N \n',V, F);
fclose(fo);
------------------------------------------------------------------------
MATLAB® Fundamentals 33
Program Results:
V= 12 m/s, F = 50.20 N
---------------------------------------------------------------------
The extension on the output file should be .txt (otherwise when you try
to open the file, MATLAB will start the import wizard). The resulting
output file will be saved and listed in the Current Folder. You can open
the file by double clicking on the output.txt file listed in the Current Folder
column on the left (see Figure 2.10). Alternatively, you can open the file by
clicking on the Open icon in the Toolstrip that brings up a screen listing
all the .m files in the Current folder. In the box labeled File name, type
in *.txt. This will bring up a screen listing of all the files with the exten-
sion .txt in the Current folder as shown in Figure 2.11. To open the file of
interest, double click on the name of the output file (in this example, the
file name is output.txt).
In earlier versions of MATLAB, you would not be able to open the output
file without having included the fclose(fo) statement in the program. But
it is still a good practice to include the fclose statement after all the output
statements in the program, or at the end of the program itself.
FIGURE 2.10
Searching for the output.txt file in Current Folder Column.
34 MATLAB® Essentials
FIGURE 2.11
Opening all files with .txt extension.
Unless you wish to plot a single point, the arguments in the plot command must
be vectors. In addition, the vectors need to be of the same length. If the argu-
ments in the plot command are scalars, the plot commands will produce just
a single point.
t = 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
V = −20.2 − 21.0 −19.4 −14.7 − 6.2 6.9 25.4 50.0 81.4 120.4 167.8
MATLAB® Fundamentals 35
Example 2.2
% Example_2_2.m
% The vectors t and V are entered into the program.
% Then a plot of V vs. t is created.
% To plot V vs. t both variables need to be vectors
% of the same length.
clear; clc;
t = [0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0];
V = [−20.2 -21.0 -19.4 -14.7 -6.2 6.9 25.4 50.0 81.4 120.4...
167.8];
% Create the plot of V vs. t.
plot(t,V), xlabel('t(s)'), ylabel('V(m/s)'), title('V vs. t'), grid;
------------------------------------------------------------------------
Program Results:
See Figure 2.12.
------------------------------------------------------------------------
V vs. t
200
150
100
V(m/s)
50
−50
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
t(s)
FIGURE 2.12
Plot of V versus t.
36 MATLAB® Essentials
REVIEW 2.3
1. Name two commands that will result in printing to the screen.
2. What is the command that will move the cursor to the next
line?
3. What is the format that will print a floating point variable to 10
spaces and to three decimal points?
4. What is the format that will print a floating point variable in
scientific notation to 12 spaces and to four decimal points?
5. What are the commands necessary to print to a file?
6. What is the command to create a plot of y versus x and what
type of variable must x and y be?
7. What are the commands that will label the x- and y-axis and
provide a title to a plot?
If a program involves creating more than one plot, you need to include the
statement figure after each plot command (except the last), otherwise only
the last plot will appear.
You may have noticed that the script for Example 2.2, contained comment lines
that described what the script is about. This is a good practice and should be imple-
mented every time you write a script.
2.9 Loops
2.9.1 The for Loop
The for loop command provides the means to repeat a series of statements
with just a few lines of code. In MATLAB, in many cases, one can avoid the
use of the for loop and achieve the same result. However, the method used
in MATLAB to achieve this may not be available in many other computer
platforms. Since we are emphasizing the computer programming building
blocks that are applicable in most, if not all, programming languages, we will
exclusively use the for loop method in the first few chapters of this book.
Syntax:
The step size may be omitted, and then MATLAB will take the step size to
be 1. Although the loop variable need not be an integer, in most cases in
this book, it will be an integer. That is because, we frequently use the loop
MATLAB® Fundamentals 37
for m = 1:20
statement;
.
.
.
statement;
end
MATLAB sets the index m to 1, carries out the statements between the for
and end statements, then returns to the top of the loop, changes m to 2 and
repeats the process. After the process has been carried out 20 times the pro-
gram exits the loop without further executing any of the statements within
the loop.
NO T E : There is no semicolon after the for and end statements.
All statements that are not to be repeated should not be within the for loop. For
example, table headings that are not to be repeated should be outside the for loop.
Also notice that statements within the for loop are indented. MATLAB does
this to make it easier to read and debug a script containing for loops. You
can have MATLAB to do final indenting by highlighting your entire script
and then entering Ctl-I.
Example 2.3
% Example_2_3.m
% This program is an example of the use of a for loop in which
% the indices of the for loop select an element of a vector.
% The indices must be an integer. In the for loop expression,
% MATLAB will take i as an integer if there is no decimal point
% in the assignment of variable i. But you can also specify i
% by the assignment int8(i) or int32(i) before it is used.
% The assignment length(t) specifies the number of elements
% in the vector t.
% The program creates a table of y1 and y2 vs t.
% 0 <= t <= 10 in steps of 0.5.
clear; clc;
% Table headings:
fprintf(' t y1 y2 \n');
fprintf('-------------------------------\n');
t=0:0.5:10;
38 MATLAB® Essentials
for i=1:length(t)
y1=t(i)^2/10;
y2=t(i)^3/100;
fprintf('%5i %10.3f %10.3f \n',i,y1,y2);
end
-----------------------------------------------------------------------
Program Results:
t y1 y2
-------------------------------
0.0 0.000 0.000
0.5 0.025 0.001
1.0 0.100 0.010
1.5 0.225 0.034
2.0 0.400 0.080
. . .
. . .
8.0 6.400 5.120
8.5 7.225 6.141
9.0 8.100 7.290
9.5 9.025 8.574
10.0 10.000 10.000
>>
-----------------------------------------------------------------------
FIGURE 2.13
How to undock Command Window from Editor Window?
MATLAB® Fundamentals 39
In the next example the loop variable is not an integer, and thus we would
not be able to use the loop variable to select an element of a vector.
Example 2.4
% Example_2_4.m
% In this example the loop variable is x which is not an integer.
% Thus, the loop variable x could not be used to select an element
% of a vector. The range of x is from -0.9 to +0.9 in steps of 0.1.
clear; clc;
% print the table headings outside of the 'for' loop:
fprintf(' x y1 y2 \n');
fprintf('--------------------------------\n');
for x = -0.9:0.1:0.9
y1=x/(1-x);
y2=y1^2;
fprintf('%5.2f %10.3f %10.3f \n',x,y1,y2);
end
% fprintf('\n %5.2f \n',x)
----------------------------------------------------------------------------
Program Results:
x y1 y2
--------------------------------
-0.90 -0.474 0.224
-0.80 -0.444 0.198
-0.70 -0.412 0.170
-0.60 -0.375 0.141
-0.50 -0.333 0.111
. . .
. . .
0.50 1.000 1.000
0.60 1.500 2.250
0.70 2.333 5.444
0.80 4.000 16.000
0.90 9.000 81.000
>>
----------------------------------------------------------------------------
You might think that the statement for x = −0.9:0.1:0.9 would create a
vector x. However, that is not the case. The process starts by setting x = −0.9.
As the program progresses back to the start of the for loop, old values of x
are overwritten by the new value of x. Try adding the statement
at the end of the for loop (by removing the % sign before the fprintf
statement in the above program) and rerunning the program. See that
you only get the last value of x, which is 0.9. Now type x =−0.9:0.1:0.9 in
the Command Window without the semicolon. See that x is now a vector.
40 MATLAB® Essentials
Example 2.5
In this example we will calculate the position and velocity of a free falling body
in a gravitational field (neglecting drag) as a function of time, t. See Figure 2.14. The
governing equations are based on Newton’s second law and can be found in any
university physics textbook.
The governing equations are
V = Vo − g t (2.1)
g t2
y = Vo t − (2.2)
2
where:
V is the velocity
y is the position pointing upward
g is the acceleration of gravity
t is the time
The following MATLAB program calculates and plots V, and y versus t, for 0 ≤ t ≤ 2 s
2
=
in steps of 0.1 s. We have taken Vo 10= m s , and g 9.81 m s . We will print a table
consisting of t, V, and y at every other time step. In addition, we will plot V versus t
and y versus t. Finally, we will determine the approximate maximum height reached
by the free falling body.
t=0 x
O
FIGURE 2.14
Ball in a gravitational field.
MATLAB® Fundamentals 41
% Example_2_5.m
% This program calculates the velocity and position of a free
% falling body vs. time.
% The velocity, V = Vo-gt
% The position, y = Vo*t-0.5*g*t^2
% The initial velocity, Vo=10 m/s, g=9.81 m/s^2
% The output goes to a file named output.txt.
% Plots of y vs. t and V vs. t are made.
% The approximate maximum height reached by the body is determined.
clear; clc;
Vo=10.0; g=9.81;
fo=fopen('output.txt','w');
t=0:0.1:2;
for i=1:length(t)
V(i)=Vo-g*t(i);
y(i)=Vo*t(i)-0.5*g*t(i)^2;
end
plot(t,V), xlabel('t(s)'), ylabel('V(m/s)'), title('V vs. t'), grid;
figure;
plot(t,y), xlabel('t(s)'), ylabel('y(m)'), title('y vs. t'), grid;
ymax=max(y);
fprintf(fo,'The approximate maximum height reached by the body =');
fprintf(fo,' %8.3f m \n',ymax);
% Table headings
fprintf(fo,'t(s) V(m/s) y(m) \n');
fprintf(fo,'--------------------------\n');
for i=1:2:length(t)
fprintf(fo,'%6.2f %10.2f %10.2f \n',t(i),V(i),y(i));
end
---------------------------------------------------------------------------
Program Results:
y vs. t
6
4
y(m)
0
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
t(s)
FIGURE 2.15
y versus t for ball in a gravitational field.
V vs. t
10
2
V(m/s)
−2
−4
−6
−8
−10
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
t(s)
FIGURE 2.16
V versus t for ball in a gravitational field.
MATLAB® Fundamentals 43
FIGURE 2.17
Preallocation message when running Example 2.5.
In running Example 2.5, you may have noticed a small orange line just to the
right of the vertical ladder (see Figure 2.17). If you use your mouse to point
on the orange line you would get the following message: “The variable ‘V’
appears to change size with every loop iteration (within a script). Consider
preallocating for speed.” This would be very important when the number
of repeats in the loop is very large; otherwise, it is not important. Although
MATLAB recommends, but does not require, the preallocation of the size of
the vector or matrix that is being generated, other programs such as C/C++
do require it. To preallocate the size of the vector that is being generated, use
MATLAB’s zeros function. In the above example, 21 v values and 21 y values
will be generated. So add the following statements before the for loop:
v=zeros(21,1) and y=zeros(21,1).
In the while loop, MATLAB will carry out the statements between the
while and end statements as long as the condition in the while statement is
satisfied. In the above example, when n = 10, none of the commands within
44 MATLAB® Essentials
the while loop will be executed and the program goes to the next command
after the end statement. Note that the statement “n = n+1” above does not
make sense algebraically, but does makes sense in the MATLAB language.
The “=” operator in MATLAB (as in many computer languages) is the assignment
operator that tells MATLAB to fetch the contents in the memory cell containing the
variable n, put its value into the arithmetic unit of the CPU, increment the variable n
by 1, and put the new value back into the memory cell designated for the variable n.
Thus, the old value of n has been replaced by the new value for n.
In this example, we will use a simpler version of Example 2.5, but this time
we will use the while loop instead of the for loop.
Example 2.6
% Example_2_6.m
% This program calculates the velocity and position of a free
% falling body vs. time.
% The program uses a while loop in place of the for loop.
% The velocity, V = Vo-gt
% The position y = Vo*t-0.5*g*t^2
% Vo=10 m/s, g=9.81 m/s^2
% The output goes to a file named output.txt.
clear; clc;
Vo=10.0; g=9.81;
fo=fopen('output.txt','w');
% Table headings
fprintf(fo,'t(s) V(m/s) y(m) \n');
fprintf(fo,'-------------------------\n');
t=0; V=0; y=0;
while t<=2
fprintf(fo,'%6.2f %10.2f %10.2f \n',t,V,y);
t=t+0.2;
V=Vo-g*t;
y=Vo*t-0.5*g*t^2;
end
----------------------------------------------------------------------------
Program Results:
t(s) V(m/s) y(m)
-------------------------
0.00 10.00 0.00
0.20 8.04 1.80
0.40 6.08 3.22
0.60 4.11 4.23
0.80 2.15 4.86
1.00 0.19 5.09
1.20 -1.77 4.94
1.40 -3.73 4.39
1.60 -5.70 3.44
1.80 -7.66 2.11
2.00 -9.62 0.38
----------------------------------------------------------------------------
Compare results obtained from Examples 2.7 and 2.8.
Are they the same?
MATLAB® Fundamentals 45
REVIEW 2.4
1. What is the objective in using a for loop?
2. What is the syntax of a for loop?
3. Should table headings that are not to be repeated be inside a
for loop?
4. If the index of a for loop is used to select an element of a vector
or a matrix, what variable type should the for loop index be?
5. What other statement type can be used to create a loop?
6. What is the major difference between a for loop and a while
loop?
Exercises
where:
b is the length of the piston rod
r is the radius of the crankshaft
ω is the rotational speed of the crankshaft in revolutions per second
Piston
Displacement
Piston rod
Journal b
s
θ
r
FIGURE 2.18
(a) Piston configuration and (b) piston position variables.
46 MATLAB® Essentials
1. Create a table of s versus t and print the results to both the screen
and to file.
2. Create a plot of s versus t.
2 2
c k c k c
y = exp − t A sin − t + B cos − t
2m m 2 m m 2 m (2.4)
Take
m = 25.0 kg
c is the damping factor = 5.0 N-s/m
k is the spring constant = 200.0 N/m
A = 5.0 m
B = 0.25 m
Unstretch
–
y0
Position Static
Equilibrium ky cy′
– y
y position
–
y+–
y0 = –
y
w M M
w w
FIGURE 2.19
Mass-spring-dashpot system.
MATLAB® Fundamentals 47
6m
Center of hoop
Vo
ϑo
3.048 m
1.98 m y
Floor
x
FIGURE 2.20
Basketball player shooting the basketball.
E2.4. A basketball player shoots the ball when he is 6 m from the center of the
hoop as shown in Figure 2.20. The ball is released at a velocity, Vo , and makes
angle ϑo = 40° with the horizontal. Using Newton’s second law and the initial
conditions and neglecting the drag on the basketball, we can determine the
following equations for the (x, y) position of the ball as a function of time, t.
x = Vo cos(ϑo )t (2.5)
g 2
y = yo + Vo sin(ϑo )t − t (2.6)
2
Take the (x, y) position of the center of the hoop to be (xf , yf ) = (6.0 m, 3.048 m),
yo = 1.98 m, and ϑo = 40º.
1. Determine the time, tf , which it takes for the ball to reach the center
of the hoop. Time, t, equals zero when the ball leaves the player’s
hands.
2. Determine the velocity, Vo , that will result in the ball reaching the
center of the hoop at time tf .
3. Create a table consisting of t, x, y for 0 ≤ t ≤ t f in steps of t f 10. Carry
variables to 4 decimal places. Print the table to an output file, includ-
ing tf and Vo .
4. Create a plot of y versus x.
Hint: Solve Equation 2.5 for Vo and substitute the expression for Vo into
Equation 2.6, giving an expression involving t, x, and y. In that expression,
set t = tf , x = x f , and y = yf . In the resulting equation, tf is the only unknown.
Use this expression in your MATLAB program to solve for tf .
48 MATLAB® Essentials
E2.5. A small sphere moving though a fluid at a slow velocity will have a
drag force acting on it, which is described by Stokes’ Law. The sphere could
be a dust particle or a raindrop moving in air, or a ball bearing moving in oil.
The drag force described by Stokes’ Law is
D = 6πRµV (2.7)
where:
D is the drag
R is the radius of the sphere
µ is the viscosity of the fluid
V is the velocity of sphere
Let us consider a steel ball bearing dropped in oil (see Figure 2.21) with an
initial velocity of zero. The ball bearing will drop with a varying velocity
until it reaches a final velocity (terminal velocity, VT). The forces acting on
the ball bearing are the gravitational force, W, buoyancy force, B, and the
drag force, D. The buoyancy force is equal the weight of the fluid displaced.
The equations for W and B are
W = ρsteel υg (2.8)
B = ρoil υg (2.9)
where:
ρsteel is the mass density of steel
ρoil is the mass density of oil
υ is the volume of sphere = 4 3 πR3
g is the gravitational constant
y B
FIGURE 2.21
Ball bearing in oil.
MATLAB® Fundamentals 49
W −B−D = 0 (2.10)
−
6πRµ g
t
V = VT 1 − e W (2.12)
E2.6. The voltage in a parallel resistance, inductor, and capacitor (RLC) circuit
(see Figure 2.22) is given by
2 2
1 1 1 1 1
v = exp − t A exp − t + B exp − t (2.13)
2 RC 2 RC LC 2RC LC
t=0
iR iL iC
+ + +
Io(t) vC
vR R vL L C
− − −
FIGURE 2.22
A parallel resistance, inductor, and capacitor (RLC) circuit.
50 MATLAB® Essentials
2.10 Input
Engineers who carry out tests on a piece of equipment may need to enter
data into an existing computer program for analysis. There are several com-
mands that may be used to enter data from a data file. These are the load,
dlread, and fscanf commands. We will discuss them one at a time. The
analysis program may also ask the user to input data from the keyboard.
To enter data from the key board, use MATLAB’s input command, which
makes the program interactive.
load filename.txt
The input file must have the same number of columns in each row and must be in
the same folder as the program loading the data file. The data file should only have
numbers. Suppose we had the following data file named atm_properties and
we wish to enter the data into a program. Here, the first column is altitude
in meters, the second column is temperature in degrees Kelvin (K), the third
column is pressure in Pascal (Pa), and the fourth column is density in
kilogram/meter3 (kg/m3).
N O T E : Before you can run the following example (Example 2.9), you need to
create the data file shown on the previous page. To do this, copy the data,
then go to MATLAB and open up a new script window and paste the data
into the new script window. Then click on the Save icon and save the file as
atm_properties.txt. To save the file as a .txt file, click on the down arrow in
the Save as type box and select All files (*.*).
Alternatively, you can open up a new script window and type in the data,
and then follow the instructions described above. Try typing or copy-
ing the following program into the Editor Window in MATLAB and
running it.
Example 2.7
% Example_2_7.m
% This program uses the load command to load the data in the file
% named atm_properties.txt into this program. Column 1 is the
% altitude, column 2 is the temperature, column 3 is the pressure
% and column 4 is the density. Altitude is in meters (m),
% temperature is in degrees Kelvin (K), pressure is in Pascal (Pa)
% and density is in (kg/m^3).
% The program also is an example of using the colon operator to
% create the vectors z,T,p and rho.
% The program also demonstrates the use of the fprintf command.
% The program prints out elements of the vectors z,T,p and rho.
clear; clc;
load('atm_properties.txt');
% establishing variable names to scanned file.
z=atm_properties(:,1);
T=atm_properties(:,2);
p=atm_properties(:,3);
rho=atm_properties(:,4);
fprintf('z(m) T(K) p(Pa) rho(m^3/kg) \n');
fprintf('-------------------------------------------\n');
for j=1:length(z)
fprintf('%5.0f %8.2f %10.3e %8.4f \n',z(j),T(j),p(j),rho(j));
end
------------------------------------------------------------------------
Program Results:
z(m) T(K) p(Pa) rho(m^3/kg)
-------------------------------------------
0 288.15 1.013e+05 1.2252
1000 281.65 8.987e+04 1.1118
2000 275.15 7.949e+04 1.0065
3000 268.65 7.010e+04 0.9091
4000 262.15 6.162e+04 0.8191
5000 255.65 5.400e+04 0.7360
>>
---------------------------------------------------------------------------
52 MATLAB® Essentials
load (atm_properties.txt);
rho = atm_properties(:,4);
with
Y=dlmread('atm_properties.txt');
z=Y(:,1);
T=Y(:,2);
p=Y(:,3);
rho=Y(:,4);
clear; clc;
Y=dlmread('atm_properties.txt');
% establishing variable names to scanned file.
z=Y(:,1);
T=Y(:,2);
p=Y(:,3);
rho=Y(:,4);
fprintf(' z(m) T(K) p(Pa) rho(m^3/kg) \n');
fprintf('------------------------------------------------------\n’);
for j=1:length(z)
fprintf('%5.0f %8.2f %10.3e %8.4f \n',z(j),T(j),p(j),rho(j));
end
A = zeros(n, m);
fi = fopen('filename.txt','r');
[A] = fscanf(fi,'%f',[n,m]);
MATLAB® Fundamentals 53
where n × m is the number of elements in the data file. The 'r' in the fopen
statement tells MATLAB that this file is for reading in data. The n × m
matrix is filled in column order. Thus, rows become columns and columns
become rows.
The following example program enters the data in atm_properties.txt into
the program.
NO T E : Before you can run program Example_2_8.m, the data file atm_properties.
txt had to be created.
Example 2.8
% Example_2_8.m
% This program uses fscanf command to load the data in the file
% named atm_propeties.txt into this program. Column 1 is the
% altitude, column 2 is the temperature, column 3 is the pressure
% and column 4 is the density. Altitude is in meters (m)
% temperature is in degrees Kelvin (K), pressure is in Pascal (Pa)
% and density is in (kg/m^3).
clear; clc;
fi = fopen('atm_properties.txt','r');
% Print A to the screen and see that columns of the data file
% became rows.
A = fscanf(fi,'%f',[4,6])
% establishing variable names to scanned file.
z=A(1,:);
T=A(2,:);
p=A(3,:);
rho=A(4,:);
fprintf('z(m) T(K) p(Pa) rho(m^3/kg) \n');
fprintf('-------------------------------------------\n');
for j=1:length(z)
fprintf('%5.0f %8.2f %10.3e %8.4f \n',z(j),T(j),p(j),rho(j));
end
------------------------------------------------------------------------
Program Results:
z(m) T(K) p(Pa) rho(m^3/kg)
-------------------------------------------
0 288.15 1.013e+05 1.2252
1000 281.65 8.987e+04 1.1118
2000 275.15 7.949e+04 1.0065
3000 268.65 7.010e+04 0.9091
4000 262.15 6.162e+04 0.8191
5000 255.65 5.400e+04 0.7360
>>
--------------------------------------------------------------------------
54 MATLAB® Essentials
If you are using MATLAB version R2016A, you will need to click on the
Command Window to enter the data. If you are not using MATLAB version
R2016A, the user can type information in the Command Window without
having to first click in the Command Window. The user should then type in
something like
In this case, the user can respond with either a y or n (without single quotation
marks). An example using this concept will be given in Chapter 3.
MATLAB® Fundamentals 55
E2.7. Write a MATLAB program that uses the input command to enter the
following three vectors:
REVIEW 2.5
1. Name four commands that can be used in a script to input data
into the workspace.
2. Which of the four commands makes the program interactive?
Example 2.9
% Example_2_9.m
% This program creates two separate plots.
% First y1=t^2/10 is plotted with 0 <= t <= 10,
% then y2=t^3/100 is plotted over the same t range.
% To plot y1 and y2 vs. and t, they need to be made vectors.
clear; clc;
t=0:0.5:10;
for n=1:length(t)
y1(n)=t(n)^2/10;
y2(n)=t(n)^3/100;
end
plot(t,y1), xlabel('t'), ylabel('y1'), grid, title('y1 vs. t');
figure;
plot(t,y2), xlabel('t'), ylabel('y2'), grid, title('y2 vs. t');
------------------------------------------------------------------------
56 MATLAB® Essentials
Program Results:
See Figure 2.23a and b.
------------------------------------------------------------------------
y1 vs. t
10
5
y1
0
0 1 2 3 4 5 6 7 8 9 10
(a) t
y2 vs. t
10
5
y2
0
0 1 2 3 4 5 6 7 8 9 10
(b) t
FIGURE 2.23
(a) Plot of y1 versus t and (b) plot of y2 versus t.
MATLAB® Fundamentals 57
t1 y1 z1 w1
t y2 z2 w2
A=
2
tn yn zn wn
t1 y1 z1 w1
t y z w
T = , Y = , Z = , W =
2 2 2 2
Then to plot Y versus T, Z versus T and W versus T all on the same graph,
we would write,
plot(T,Y,T,Z,T,W);
plot(A(:,1),A(:,2),A(:,1),A(:,3),A(:,1),A(:,4))
To identify which curve goes with which variable, you can add text to the
plot with the command,
text(x,y,'text statement');
where (x, y) are the coordinates on the graph where the text statement
will start.
Multiple curves on the same graph can be distinguished by color coding
the curves.
Available color types:
black 'k'
blue 'b'
green 'g'
red 'r'
cyan 'c'
yellow 'y'
58 MATLAB® Essentials
solid (default)
dashed '--'
dashed-dot '-.'
dotted ':'
Alternatively, you can create a marker plot of discrete points (without a line)
by using one of these marker styles:
point '.'
plus '+'
star '*'
circle 'o'
x-mark 'x'
diamond 'd'
The legend command may also be used in place of the text command to
identify the curves. The format for the legend command is
legend('text1', 'text2')
The legend box may be moved by clicking on the box and dragging it to the
desired position.
You can also change the axis limits in a plot by using the command
Example 2.10
The following example illustrates a multiple plot program:
% Example_2_10.m
% This program creates a simple table and a multiple plot.
% First a table of y1=t^2/10 and y2=t^3/100 is created.
% To plot y1, y2 vs. and t, they need to be made vectors.
% y1 and y2 vs. t are plotted on the same graph.
clear; clc;
t=0:10;
for n=1:length(t)
y1(n)=t(n)^2/10;
y2(n)=t(n)^3/100;
end
MATLAB® Fundamentals 59
Program Results:
t y1 y2
-------------------------------------
0.0 0.0000 0.0000
1.0 0.1000 0.0100
2.0 0.4000 0.0800
3.0 0.9000 0.2700
4.0 1.6000 0.6400
5.0 2.5000 1.2500
6.0 3.6000 2.1600
7.0 4.9000 3.4300
8.0 6.4000 5.1200
9.0 8.1000 7.2900
10.0 10.0000 10.0000
>>
See Figure 2.24.
------------------------------------------------------------------------
y1 and y2 vs. t
10
6
y1,y2
3
y1 y2
2
y1
1 y2
0
0 1 2 3 4 5 6 7 8 9 10
t
FIGURE 2.24
Plots of y1 and y2 on the same graph.
Example 2.11
The following example illustrates the plotting of trigonometric functions. The exam-
ple also illustrates that simple arithmetic can be used in the arguments of the trig-
onometric functions. This is also true for other built-in MATLAB functions. If the
resulting curves are not smooth than we would need to use more points to properly
display the curves.
% Example_2_11.m
% This script calculates both sin(2x/3), sin(2x/3)^2
% and cos(2x/3+pi) for -pi <= x <= pi. The x domain is subdivided
% into 50 subdivisions. The script plots the 3 functions and
% determines the absolute maximum values of the vectors fsin, fsinsq
% and fcos and prints those values to the screen.
clear; clc;
x=-pi:2*pi/50:pi;
for i=1:length(x)
fsin(i)=sin(2*x(i)/3);
fsinsq(i)=sin(2*x(i)/3)^2;
fcos(i)=cos(2*x(i)/3+pi);
end
MATLAB® Fundamentals 61
fsin_max=max(abs(fsin)); fcos_max=max(abs(fcos));
fsinsq_max=max(fsinsq);
fprintf('fsin_max=%10.5f, fcos_max=%10.5f \n',fsin_max, fcos_max);
fprintf('fsinsq_max=%10.5f \n',fsinsq_max);
plot(x, fsin, x,fcos,'--',x, fsinsq,'-.'), xlabel('x'),
ylabel('fsin, fcos, fsinsq'), grid,
title('fsin, fcos, fsinsq vs. x'), legend('fsin','fcos','fsi nsq');
-------------------------------------------------------------------------
Program Results:
From the Command Window:
0.8
0.6
0.4
fsin,fcos,fsinsq
0.2
−0.2
−0.4
−0.6
fsin
fcos
−0.8 fsinsq
−1
−4 −3 −2 −1 0 1 2 3 4
x
FIGURE 2.25
Plot of fsin, fcos, and fsinsq versus x.
62 MATLAB® Essentials
Example 2.12
% Example_2_12.m
% This script is a modification of Example 2.5. In this script
% both y and V axes are plotted on the same graph. The y axis
% is on the left side and the V axis is on the right side.
clear; clc;
Vo=10.0; g=9.81; t=0:0.1:2;
for i=1:length(t)
V(i)=Vo-g*t(i); y(i)=Vo*t(i)-0.5*g*t(i)^2;
end
plotyy(t,y,t,V), xlabel('t(s)'), title('y vs. t and V vs. t'), grid,
yyaxis left, axis([0 2 0 10]), ylabel('y(m)'), text(0.32,2.5,'y');
yyaxis right; axis([0 2 -10 10]), ylabel(' V(m/s)'), text(0.6,5.0,'V');
------------------------------------------------------------------------
Program Results:
See Figure 2.26.
----------------------------------------------------------------------
6
V
4
2
V(m/s)
y(m)
5 0
−2
−4
y
−6
−8
0 −10
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
t(s)
FIGURE 2.26
Plot of y versus t and V versus t on the same graph.
MATLAB® Fundamentals 63
Example 2.13
% Example_2_13.m
% This program is an example of the use of the subplot command.
% Values of y1, y2, y3 and y4 are constructed as
% vectors. Separate plots of y1 vs. t, y2 vs. t, y3 vs. t,
% and y4 vs. t are plotted on the same page.
clc; clear;
t=0:0.5:10;
for n=1:length(t)
y1(n)=t(n)^2/10;
y2(n)=sin(pi*t(n)/10);
y3(n)=exp(t(n)/2);
y4(n)=sqrt(t(n));
end
subplot(2,2,1),
plot(t,y1), grid, title('y1 vs. t'), xlabel('t''), ylabel('y1');
subplot(2,2,2),
plot(t,y2), grid, title('y2 vs. t'), xlabel('t'), ylabel('y2');
subplot(2,2,3),
plot(t,y3), grid, title('y3 vs. t'), xlabel('t'), ylabel('y3');
subplot(2,2,4),
plot(t,y4), grid, title('y4 vs. t'), xlabel('t'), ylabel('y4');
----------------------------------------------------------------------------
Program Results:
See Figure 2.27.
---------------------------------------------------------------------------
bar(y)
bar(x,y)
bar(___, width)
bar(___, style)
bar(___, color)
64 MATLAB® Essentials
y1 vs. t y2 vs. t
10 1
5 0.5
y1
y2
0 0
0 5 10 0 5 10
t t
y3 vs. t y4 vs. t
150 4
3
100
2
y3
y4
50
1
0 0
0 5 10 0 5 10
t t
FIGURE 2.27
Plots of y1, y2, y3, and y4 versus t on the same page.
Example 2.14
In this example, we compare the profit percentage gained for year 2015 for Companies
A, B, C, D, E, F, and G. These are given in Table 2.1
% Example_2_14.m
% This script is an example of creating a bar chart.
% The script lists and plots the percentage gains in profits for
% several companies for the year 2015.
clear; clc;
y = [2.51 -0.13 3.16 4.72 1.2 6.5 3.8];
bar(y,0.4);
ylabel('% profit, year 2015');
title('1=CO.A, 2=CO.B, 3=CO.C, 4=CO.D, 5=CO.E, 6=CO.F, 7=CO.G');
----------------------------------------------------------------------
Program Results:
See Figure 2.28.
-----------------------------------------------------------------------
MATLAB® Fundamentals 65
TABLE 2.1
Companies Profits Percentage Gain for 2015
Company % Profit Gain for Year 2015
A 2.51
B −0.13
C 3.16
D 4.72
E 1.60
F 6.50
G 3.80
5
% profit, year 2015
−1
1 2 3 4 5 6 7
FIGURE 2.28
Bar chart. Percent profit gain for several companies for year 2015.
X = 1:5;
labels = {'US stocks','foreign stocks','mutual funds',...
'bonds','cash'};
pie(X,labels)
66 MATLAB® Essentials
Example 2.15
Suppose we wished to plot the percentage of several different types of investments
made by a particular investor. Table 2.2 gives the percentage of different types of
investments for that individual.
The program follows:
% Example_2_15.m
% This program gives the percentage of various types of investments
% made by a particular individual. The percentages are displayed in
% a pie chart.
clear; clc;
x=[43 12 15 20 10];
labels = {'US stocks','foreign stocks','mutual funds',...
'bonds','cash'};
pie(x, labels);
-----------------------------------------------------------------------
Program Results:
See Figure 2.29.
-------------------------------------------------------------------------
TABLE 2.2
Investment Percentages
Investments Percentage
US stocks 43
Foreign stocks 12
Mutual funds 15
Bonds 20
Money market 10
cash
bonds
US stocks
mutual funds
foreign stocks
FIGURE 2.29
Pie chart for several different types of investments.
MATLAB® Fundamentals 67
Example 2.16
• The sprintf Command
The sprintf is the same as fprintf command except that it returns the print data
as a MATLAB variable rather than writing to the Command Window or to a file.
When plotting several different plots on the same page, you may wish to vary the
titles of the plots depending on the specific variable defined in the program. This is
demonstrated in the following example:
% Example_2_16.m
% This program is an example of the use of the subplot and
% the sprintf commands.
% Plots of y=sin(k*pi*t/L) for several values of k are created and
% plotted on the same page.
clc; clear;
t=0:0.1:10;
k=[2 4 6 8];
L=10;
for m=1:length(k)
for n=1:length(t)
y(n)=sin(k(m)*pi*t(n)/L);
end
subplot(2,2,m), plot(t,y), xlabel('t'), ylabel('y'), grid,
title(sprintf('y vs.t, k=%3i \n',m));
end
-------------------------------------------------------------------------
Program Results:
See Figure 2.30.
-----------------------------------------------------------------------
y vs. t, k = 1 y vs. t, k = 2
1 1
0 0
y
−1 −1
0 5 10 0 5 10
t t
y vs. t, k = 3 y vs. t, k = 4
1 1
0 0
y
−1 −1
0 5 10 0 5 10
t t
FIGURE 2.30
Four plots of y versus t, all on one page. Each plot is for a different value of k.
68 MATLAB® Essentials
Exercises
t = [ 0 0.04 0.08 0.12 0.16 0.20 0.24 0.28 0.32 0.36 0.40 0.44 0.48 0.52 0.56 0.60 ]
T_ fluid = [20.0 22.9 25.2 27.0 28.3 29.5 30.3 31.0 31.9 32.2 32.5 32.7 32.8 32.9]
In MATLAB, create a plot of both T_sphere and T_ fluid versus t on the same
graph, t is in seconds and T_sphere and T_ fluid are in degrees C.
E2.9. This exercise involves the x position and x component of the velocity,
u, of a package dropped from an airplane as a function of time, t. These vari-
ables are specified in vectors x and u and t, respectively.
t = [ 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 ]
x = [ 0.0 23.6 44.7 63.6 80.6 95.8 109.5 121.7 132.7 142.4 150.9]
u = [ 50.0 44.6 39.9 35.8 32.2 28.9 25.9 23.1 20.6 18.2 15.9]
Create a MATLAB program that will plot x versus t and u versus t as two
separate plots, but both on the same page.
Example:
ylabel('\omega'), title('\omega vs. \beta'), text(10,5,'\omega');
For an additional list of Greek symbols and some special characters, see
Appendix A. You may also occasionally need to print a “'” character in your label
or title. In this case, use a double-quotation mark as shown here '' to escape the
single-quote character in your string. Thus, to generate the plot title “Signal 'A'
vs. Signal 'B'”, you would type
REVIEW 2.6
1. When there is more than one function plotted on a graph, what
are the ways to identify which curve goes with which function?
2. What is the name of the function that will allow you to plot
several graphs on one page?
3. How does one enter Greek symbols into a plot?
4. What are the commands that will allow you to enter text onto
a plot once the plot has been created?
70 MATLAB® Essentials
Projects
P2.1. A tennis player on serve wishes to place the tennis ball close to the
outside line of the service box when the ball hits the ground (see Figure P2.1a
and b). The horizontal distance from the point where the ball leaves the
racket to where the ball hits the ground is 19.33 m. The vertical distance, yo ,
above the ground when the ball leaves the racket is 2.36 m. The angle that the
ball makes with the horizontal on leaving the players racket is 5.7° pointing
down. Neglecting drag, the governing equations describing the motion of
the ball are
x = Vo cos(ϑ) t (P2.1a)
g 2
y=− t − Vo sin(ϑ) t + yo (P2.1b)
2
1. Determine the time, tf . Time, t, equals zero when the ball leaves the
racket.
2. Determine the velocity, Vo , that will result in the ball reaching the
ground at time tf .
Ball path
Ball leaves
racket
Net
(a)
y
5.7° Ball leaves racket
FIGURE P2.1
Tennis player on serve: (a) plan view and (b) vertical view.
MATLAB® Fundamentals 71
P2.2. A batter in a baseball game hits a ball to right center field. The ball leaves
the bat at a 30° angle with the horizontal at a speed of Vo and at a height of
1.5 m above the ground. The center fielder is 71 m from home plate and the
angle that the horizontal line connecting the center fielder with home plate
makes angle of 10° with the horizontal path of the ball, see Figure P2.2a
and b. The center fielder sees the direction of the fly ball and starts to run
toward the path of the ball at an average speed, S and 0.5 s after the ball is
hit. The center fielder catches the ball when it is just 1.8 m above the ground
and 91 horizontal meters from the initial position of the ball as it leaves the bat.
Neglecting drag, the governing equations describing the motion of the ball are
x = Vo cos(ϑ ) t (P2.2a)
g 2
y=− t − Vo sin(ϑ ) t + yo (P2.2b)
2
10°
71 m 91 m
y Vo Ball is caught
Baseball
leaves bat 30°
Ground
1.5 m 1.8 m
x
91 m
(b)
FIGURE P2.2
Batter hitting baseball: (a) Plan view and (b) vertical view.
72 MATLAB® Essentials
g
λz λ R
p = po 1 − (P2.3a)
To
T = To − λz (P2.3b)
p
ρ= (P2.3c)
RT
where:
z is the altitude
To = 288.15 K (the temperature at z = 0)
po = 1.01325 × 105 Pa (the pressure at z = 0)
R = 287 J/(kg-K) (the gas constant for air)
g = 9.81 m/s2 (the gravitational constant for air)
λ = 0.0065 K/m (the lapse rate)
ρ is the air density (kg/m3)
TABLE P2.1
Specific Volume and Pressure versus Temperature
T (K) v (m3/kmol) p (bar)
1000
800
600
y
FIGURE P2.3
Two cars on a collision path.
74 MATLAB® Essentials
yc = y1 + ( xc − x1 ) × tan(60°) (P2.5)
yc = y2 + ( x2 − xc ) × tan(45°) (P2.5)
y2 − y1 + x1 tan(60°) + x2 tan(45°)
xc = (P2.5)
tan(60°) + tan(45°)
The distance travelled by each car from the initial state to the collision state is
d1 = ( xc − x1 )2 + ( yc − y1 )2 = V1 tc (P2.5)
d2 = ( x2 − xc )2 + ( yc − y2 )2 = V2 tc (P2.5)
where tc = time of collision. Equating the tc from both the above equations give
d1 d2 d
= → V2 = V1 2 (P2.5)
V1 V2 d1
On line 1:
x(t) = x1 + V1 cos(60°) t , y(t) = y1 + V1 sin(60°) t (P2.5)
On line 2:
x(t) = x2 − V2 cos( 45°)t , y(t) = y2 + V2 sin( 45°) t (P2.5)
3. Take t = 0: tc /5: tc and plot the two lines and the two car’s positions
at ti , shown as small circles, all on the same graph.
P2.6. A formula describing the fluid level, h(t), in a tank as the fluid dis-
charges through a small circular orifice (see Figure P2.4) is
Cd A o
h = ho − 2g t (P2.6)
2 AT
where:
Cd is the discharge coefficient
ho is the fluid level in the tank at time, t = 0
Ao is the circular area of the orifice having diameter d
AT is the circular cross-sectional area of the tank having diameter D
P2.7. When a fluid flows through a pipe there is a pressure drop that is pro-
portional to the pipes length (see Figure P2.5). For a pipe having a circular
cross section, the pressure drop, p1 − p2 [1] is given by
Vo
FIGURE P2.4
Fluid discharging through a small orifice.
76 MATLAB® Essentials
1 2
FIGURE P2.5
Fluid flow through a pipe.
ρV 2 L
p1 − p2 = f (P2.7)
2 D
where:
ρ is the fluid density (kg/m 3 )
V is the average fluid velocity in the pipe (m/s)
D is the pipe diameter (m)
L is the pipe length between points 1 and 2 (m)
f is the friction factor
The friction factor has been determined by experiment. For smooth pipes a
formula that approximates the experimental data is [5]
where:
ρVD
Re = (Reynolds number) (P2.7)
µ
Re = [5.0e3 7.5e3 1.0e4 2.5e4 5.0e4 7.5e4 1.0e5 2.5e5 5.0e5 7.5e5 1.0e6
2.5e6 5.0e6 ].
Take ρ = 1000 kg/m 3 , L = 50 m , D = 0.15 m , and µ = 1.52 × 10 −3 N − s m 2
b 2 = s2 + r 2 − 2s r cos θ (P2.8a)
MATLAB® Fundamentals 77
or
s2 − (2 r cos θ ) s + ( r 2 − b 2 ) = 0 (P2.8b)
where:
b is the length of the piston rod
r is the radius of the crankshaft
s=
1
2 ( )
2r cos θ + 4r 2 cos 2 θ − 4(r 2 − b 2 ) = r cos θ + r 2 (cos 2 θ − 1) + b 2
or
The piston is constrained to move in the vertical direction and its position, s,
varies as the crankshaft rotates. The angle, θ, varies with time, t, and can be
expressed in terms of the rotational speed, ω, of the crankshaft. The angle ν
is thus given by
θ = 2πωt (P2.8d)
k 2 k 2
c c c
y = exp − t A cos − t + B sin − t (P2.9)
2m m 2m m 2m
N N−s c A
m = 25 kg , k = 200 , c=5 , A = 0.5 m , B = ×
m m 2m 2
k c
−
m 2m
c
yenv = ± A exp − t
2m
P2.10. In this project we consider the voltage, v, of a parallel RLC circuit when
at t = 0, the switch is opened. See Figure 2.22. The governing equation for v,
depends on the values of R, L, and C.
If (1 2RC )2 < 1 LC , then the solutions are decaying sinusoids over time
(underdamped) and the governing equation for v is
1 2 1 2
1 1 1
v = exp − t A cos − t + B sin − t (P2.10)
2RC LC 2RC LC 2RC
For a complete derivation of Equation P2.10 see Project P2.7 in [3,5]. The
coefficients A and B are to be determined by initial conditions, which are
beyond the scope of this book.
MATLAB® Fundamentals 79
Create a MATLAB program that will calculate and plot v(t) for
0 ≤ t ≤ 500 µsec in steps of 5 μsec using the following parameters:
P2.11. This project involves determining the rate that heat, q, which is trans-
ferred into a house per unit surface area from a section of the exterior walls
shown in Figure P2.6. The wall consists of plaster board, insulation, wood
sheathing, and brick.
The governing equation describing the rate that heat is transferred, q, into
a house from the wall section [6] shown in Figure P2.6 is
To − Ti
q= (P2.11)
1 L1 L2 L3 L4 1
+ + + + +
ho k1 k2 k3 k4 hi
where:
ho is the outside convective heat transfer coefficient
hi is the inside convective heat transfer coefficient
k1 is the thermal conductivity of brick
k2 is the thermal conductivity of wood sheathing
k3 is the thermal conductivity of insulation
k4 is the thermal conductivity of plaster board
Temperature profile
To
Inside
Outside
Outside brick
Ti
L1 L2 L3 L4
Plaster board
FIGURE P2.6
Heat flow through exterior wall.
80 MATLAB® Essentials
Create a MATLAB program that determines the rate that heat flows into a
house per unit surface area due to the section of the wall described above.
Take To to vary from 25°C to 40°C in steps of 1.0°C and Ti = 20°C. Create
a table containing To and q, include table headings with units. Also, plot q
versus To .
The thickness, L, of each material follows:
=L4 1=
.3 cm, L=
3 10 cm, L2 1=
.3 cm and L1 0.7 cm
W W W
k4 = 0.48 , k3 = 0.05 , k2 = 0.11
m−C m−C m−C
and
W W W
k1 = 0.69 , ho = 56.8 2 and hi = 11.4 2
m−C m −C m −C
References
1. Bober, W., Kenyon, R.A., Fluid Mechanics, John Wiley & Sons, New York, 1980.
2. Bober, W., The use of the Swamee-Jain formula in pipe network problems,
Journal of Pipelines, 4, 315–317, 1984.
3. Bober, W., Introduction to Numerical and Analytical Methods with MATLAB for
Engineers and Scientist, CRC Press, Boca Raton, FL, 2014.
4. Thomson, W. T., Theory of Vibration with Applications, Prentice Hall, Englewood
Cliffs, NJ, 1972.
5. Bober, W., Stevens, A., Numerical and Analytical Methods with MATLAB for
Electrical Engineers, CRC Press, Boca Raton, FL, 2012.
6. Holman, J.P., Heat Transfer, 9th Ed., McGraw-Hill, New York, 2002.
3
Conditional Operators, Built-in
Functions with Vector Arguments,
MATLAB®’s Interp1 Function,
and Some Scalar and Vector Operations
3.1 Introduction
In this chapter, we cover the next building block in basic programming,
one that exists in most programming languages and that is the Conditional
Operators. The first conditional operator discussed is the if-else com-
mand. Next we cover the if-elseif-else ladder, followed by a description
of the Switch Group. Also, in this chapter, we discuss working with built-
in functions with vector arguments, MATLAB®’s interp1 function and
some scalar and vector operations, including element-by-element operations.
if logical expression
statement;
statement;
else
statement;
statement;
end
81
82 MATLAB® Essentials
If the logical expression is true, then only the upper set of statements is
executed. If the logical expression is false, then only the bottom set of state-
ments is executed.
Logical expressions are of the form
a == b; a <= b;
a < b; a >= b;
a > b; a ~= b; (a not equal to b)
The following example illustrates the use of both the if command and the
input command.
In Example 3.1, we use the fprintf command just before the input
NO T E 1 :
command, to provide the user with more directions than can be given by the
input command itself.
NO T E 2 : When the input command is executed, the Run icon in the Editor
Window changes to a Pause icon (see Figure 3.1).
Example 3.1
% Example_3_1.m
% This program uses the input command and an if statement to
% determine if the output is to go to the screen or to a file. The
% variables y1 and y2 are made vectors so that these variables can
% be printed outside the for loop that created them. As vectors,
% they can also be plotted.
clear; clc;
t=0:0.5:5;
FIGURE 3.1
MATLAB’s menu push button figure.
Conditional Operators, Built-in Functions with Vector Arguments 83
for j=1:length(t)
y1(j)=t(j)^2/10;
y2(j)=t(j)^3/100;
end
fprintf('Do you wish to print the output to \n');
fprintf('the screen or to a file? \n');
response=input('Enter s for screen or F for file \n','s');
% Note, since we entered 's' in the input statement, you do not
% need to enclose your answer in single quotation marks.
if response=='s'
% Table headings:
fprintf(' t y1 y2 \n');
fprintf('---------------------------\n');
for j=1:length(t)
fprintf('%3.1f %10.3f %10.3f \n', ...
t(j),y1(j),y2(j));
end
end
if response=='F'
fo=fopen('output.txt','w');
% Table headings:
fprintf(fo,' t y1 y2 \n');
fprintf(fo,'---------------------------\n');
for j=1:length(t)
fprintf(fo,'%3.1f %10.3f %10.3f \n',...
t(j),y1(j),y2(j));
end
end
--------------------------------------------------------------------------------------------------
Program Results (either from the screen or from the file “output.txt”):
t y1 y2
---------------------------
0.0 0.000 0.000
0.5 0.025 0.001
1.0 0.100 0.010
1.5 0.225 0.034
2.0 0.400 0.080
2.5 0.625 0.156
3.0 0.900 0.270
3.5 1.225 0.429
4.0 1.600 0.640
4.5 2.025 0.911
5.0 2.500 1.250
-----------------------------------------------------------
The if-elseif-else ladder works from top down. If the top logical expres-
sion is true, the statements related to that logical expression are executed,
and the program will leave the ladder. If the top logical expression is not
true, the program moves to the next logical expression. If that logical expres-
sion is true, the program will execute the group of statements associated
with that logical expression and leave the ladder. If that logical expression is
not true, the program moves to the next logical expression and continues the
process. If none of the logical expressions are true the program will execute
the statements associated with the else statement. The else statement is
not required. In that case, if none of the logical expressions are true, no state-
ments within the ladder will be executed.
--------------------------------------------------------------
Suppose in Example 3.1, we had more than two choices. For example, we had the
choice of printing to the screen, printing to a file, exiting the program, or opening
the edit window to create a new program. The following program uses the if-
elseif-else ladder and the input statement to decide which choice to select.
Example 3.2
% Example_3_2.m
% First the script determines y1 and y2 as functions of t. The
% script then uses the input command and the if-elseif ladder to
% determine if the program prints the results to the screen,
% prints the results to a file, exits the program or opens the edit
% window to create a new script.
clear; clc;
t=0:0.5:5;
for j=1:length(t)
y1(j)=t(j)^2/10;
y2(j)=t(j)^3/100;
end
fprintf('If you wish to print the output to the screen enter S \n');
fprintf('If you wish to print the output to a file enter F \n');
fprintf('if you wish to close the program enter C \n');
fprintf('If you wish to open the edit window enter E \n');
fprintf('Enter your response without single quotation marks \n');
response=input('Enter S, F, C or E \n','s');
if response=='S'
% Table headings:
fprintf(' t y1 y2 \n');
fprintf(' ------------------------------\n');
Conditional Operators, Built-in Functions with Vector Arguments 85
for j=1:length(t)
fprintf('%5.1f %10.3f %10.3f \n',t(j),y1(j),y2(j));
end
elseif response=='F'
fo=fopen('output.txt','w');
% Table headings:
fprintf(fo,' t y1 y2 \n');
fprintf(fo,'-------------------------------\n');
for j=1:length(t)
fprintf(fo,'%5.1f %10.3f %10.3f \n',t(j),y1(j),y2(j));
end
fclose(fo);
elseif response=='C'
quit;
elseif response=='E'
edit;
end
------------------------------------------------------------------------
for m = 1:20
statement(s);
if m > 10
break;
end
end
In the above example, when m becomes greater than 10, the program
leaves the for loop and moves on to the next statement outside the for
loop.
----------------------------------------------------------------
between table values x1 and x2 , then the general linear interpolation formula,
based on similar triangles, in terms of y and x is
( y2 − y1 )× ( x − x1 )
y = y1 + (3.1)
x2 − x1
The next example is an interactive program, where the user is asked to enter
an altitude at which he/she wishes to know the atmospheric properties. The
program uses the if-elseif ladder to determine the closest surrounding
altitude to the entered altitude. It then calculates the atmospheric properties
of temperature, pressure, and density by linear interpolation. In MATLAB,
the easiest and most efficient way to solve this interpolation problem is to use
MATLAB’s interp1 function. However, if you do not have MATLAB avail-
able, but have availability a different computer programming platform used
by engineers, then you would probably need to solve the interpolation prob-
lem by one of the two examples listed below. The second one, Example 3.4 is
more efficient than Example 3.3 and should always be used in preference to
Example 3.3. We give Example 3.3 as a demonstration of the use of the if-
elseif ladder. Later we will use the MATLAB’s interp1 function to solve
the problem.
Example 3.3
% Example_3_3.m
% This program loads data from a file named atm_properties.txt
% The program asks the user to enter an elevation at which atmospheric
% properties are to be determined by linear interpolation.
% The altitude range is from 0 to 5000 m.
Conditional Operators, Built-in Functions with Vector Arguments 87
Program Results:
Enter the altitude at which atmospheric properties
are to be determined. Altitude range is from 0 to 5000 m
4380
T=259.68(K), p=5.8728e+04(Pa) rho=0.7875(kg/m^3)
>>
------------------------------------------------------------------------------
load atm_properties.txt
% establishing variable names to loaded data.
zt=atm_properties(:,1);
Tt=atm_properties(:,2);
pt=atm_properties(:,3);
rhot=atm_properties(:,4);
with
zt=[0 1000 2000 3000 4000 5000];
Tt=[288.15 281.65 275.15 268.65 262.15 255.65];
pt=[10.133 8.9869 7.9485 7.0095 6.1624 5.4002]*1.0e+004;
rhot=[1.2252 1.1118 1.0065 0.9091 0.8191 0.7360];
A more efficient way to solve the problem with far fewer lines of code
is to use a single for loop and an if statement to determine the closest
interval to the entered altitude by the user, thus, reducing the number
of lines in the program. This is demonstrated in the following example.
This becomes important when the number of conditions in the program
is large.
Example 3.4
% Example_3_4.m
% This program enters the data shown in atm_properties.txt directly
% into the program as vectors.
% The program then asks the user to enter an elevation at which the
% atmospheric properties are to be determined by linear interpolation.
% The atmospheric properties are then printed to the screen.
% The program uses a for loop and a compound if statement to determine
% the closest interval to the entered altitude. The properties in
% this interval will be used in the interpolation formula.
% Temperature is in degrees Kelvin (K), pressure is in Pascal (Pa) and
% density is in kg/m^3.
clear; clc;
zt=[0 1000 2000 3000 4000 5000];
Tt=[288.15 281.65 275.15 268.65 262.15 255.65];
pt=[10.133 8.9869 7.9485 7.0095 6.1624 5.4002]*1.0e+004;
rhot=[1.2252 1.1118 1.0065 0.9091 0.8191 0.7360];
fprintf('Enter the altitude at which atmospheric properties \n');
z=input('are to be determined. Altitude range is from 0 to 5000 m \n');
for i=1:length(zt)-1
if z>=zt(i)&& z<zt(i+1)
z1=zt(i); z2=zt(i+1); T1=Tt(i); T2=Tt(i+1);
p1=pt(i); p2=pt(i+1); rho1=rhot(i); rho2=rhot(i+1);
break;
end
end
T=T1+(T2-T1)*(z-z1)/(z2-z1);
p=p1+(p2-p1)*(z-z1)/(z2-z1);
rho=rho1+(rho2-rho1)*(z-z1)/(z2-z1);
fprintf('T=%6.2f(K), p=%10.4e(Pa) rho=%6.4f(kg/m^3) \n',T,p,rho);
-------------------------------------------------------------------------------
Conditional Operators, Built-in Functions with Vector Arguments 89
Program Results:
Enter the altitude at which atmospheric properties
are to be determined. Altitude range is from 0 to 5000 m
1350
T=279.38(K), p=8.6235e+04(Pa) rho=1.0749(kg/m^3)
>>
--------------------------------------------------------------------------------------
switch(var)
case var1
statement(s);
case var2
statement(s);
case var3
statement(s);
otherwise
statement(s);
end
where var takes on the possible values var1, var2, var3, and so on.
If var equals var1, those statements associated with var1 are executed
and the program leaves the Switch Group. If var does not equal var1, the
program tests if var equals var2, and if yes, the program executes those
statements associated with var2 and leaves the Switch Group. If var does
not equal any of var1, var2, and so on, the program executes the state-
ments associated with the otherwise statement. If var1, var2, and so on
are strings, they need to be enclosed by single quotation marks. It should
be noted that var cannot be a logical expression, such as var1 > = 80.
The following example illustrates the use of the Switch Group in a
MATLAB program.
Example 3.5
% Example_3_5.m
% This program is a test of the switch statement.
clear; clc;
var = 'a';
x = 5;
switch(var)
case 'b'
z = x^2;
case 'a'
z = x^3;
90 MATLAB® Essentials
otherwise
z=0;
end
fprintf(' z = %6.1f \n',z);
--------------------------------------------------------------------------
Program Results:
z = 125.0
>>
-----------------------------------------------------------------------
Example 3.6
% Example_3_6.m
% This program uses MATLAB's menu function and the if-elseif ladder
% to determine the density of a gas by the ideal gas law.
% The gas is selected by the user by clicking on a push button in
% the menu display.
clear; clc;
p=2*1.013e+5; T=350.0;
Rt=[287 2077 4121 297 260];
k= menu('choose a gas','air','helium','hydrogen','nitrogen','oxygen');
if k==1
R=Rt(1);
fprintf('The gas is Air \n');
elseif k==2
R=Rt(2);
fprintf('The gas is Helium \n');
elseif k==3
R=Rt(3);
fprintf('The gas is hydrogen \n');
elseif k==4
R=Rt(4);
fprintf('The gas is Nitrogen \n');
elseif k==5
R=Rt(5);
fprintf('The gas is Oxygen \n');
end
rho=p/(R*T);
fprintf('The density, rho, is based on the ideal gas law \n');
fprintf('T=%5.1fK p=%10.4ePa rho=%7.4fkg/m^3 \n',T,p,rho);
----------------------------------------------------------------------------
Conditional Operators, Built-in Functions with Vector Arguments 91
FIGURE 3.2
Menu display.
The menu display that pops up (upper left corner of the screen) is shown in Figure 3.2.
I clicked on the nitrogen button and got the following result:
Program Results:
The gas is Nitrogen
The density, rho, is based on the ideal gas law
T=350.0K p=2.0260e+05Pa rho=1.9490kg/m^3
>>
-------------------------------------------------------------------------------
REVIEW 3.1
1. What statement is frequently used to establish two conditional
paths?
2. What series of statements is used to establish several condi-
tional paths?
3. List the various types of logic statements that can be used with
the if-else and if-elseif-else ladder.
4. Is the else statement required with either the if-else or the
if-elseif–else ladder?
5. What statement group and a MATLAB’s function are alterna-
tives to the if-elseif-else ladder?
92 MATLAB® Essentials
TABLE 3.1
Score Range for Letter Grade
Letter Grade Score Range
A 100 to 90
B 89 to 80
C 79 to 70
D 69 to 60
F Less than 60
Exercises
E3.1. The numerical grades on an exam are listed in the vector labeled scores.
Scores = [92 85 73 83 75 85 65 76 96 84 76 81 55 76 94 65 84 62 78 80 74 62 84
76 70 88 74 82 70 86]. Each score will be assigned a letter grade as indicated
in the Table 3.1.
Write a MATLAB program that will determine the number of grades in
each letter grade category and plot the result as a bar chart (see Example 2.14).
E3.2. Repeat Example 3.6, but this time use the switch Statement instead of
the if-elseif ladder.
Example 3.7
% Example_3_7.m
% This program demonstrates that if the argument in a built in
% function, such as MATLAB's sine function, is a vector, the result
% will also be a vector.
clear; clc;
% Define vector x;
x=0:30:360;
% Let y1 be the sine of a vector x where x is in degrees.
% Running sind with vector x as an argument will return a vector:
y1 = sind(x);
% Thus, y1 is a vector.
% Let y2(n) be the sine of the nth element of x. We will use a for
% loop to calculate each value y2(n) and then compare y1 and y2.
Conditional Operators, Built-in Functions with Vector Arguments 93
for n=1:length(x)
y2(n)=sind(x(n));
end
% Table headings
fprintf(' x y1 y2 \n');
fprintf('------------------------------------\n');
for n=1:length(x)
fprintf('%5.1f %8.5f %8.5f \n',x(n),y1(n),y2(n))
end
-----------------------------------------------------------------------------
Program Results:
x y1 y2
------------------------------------
0.0 0.00000 0.00000
30.0 0.50000 0.50000
60.0 0.86603 0.86603
90.0 1.00000 1.00000
120.0 0.86603 0.86603
150.0 0.50000 0.50000
180.0 0.00000 0.00000
. . .
. . .
-------------------------------------------------------------------------------
Yi = interp1(X,Y,Xi)
where X and Y are a set of known (x, y) data points and Xi is the set of x
values at which the set of y values, Yi, are to be determined by linear inter-
polation. Arrays X and Y must be of the same length. Note: If Xi is a vector,
then Yi will also be a vector. The function interp1 can also be used for
interpolation methods other than linear interpolation, and this is covered in
Chapter 9 on Curve Fitting. In the next example, we modify Example 3.4 by
using MATLAB’s interp1 function to interpolate for the atmospheric proper-
ties at an altitude entered from the keyboard.
94 MATLAB® Essentials
Example 3.8
% Example_3_8.m
% This program enters the data shown in atm_properties.txt directly
% into the program as vectors.
% The program then asks the user to enter an elevation at which the
% atmospheric properties are to be determined by linear interpolation.
% The atmospheric properties are then printed to the screen.
% The program uses MATLAB's interp1 function to do the interpolation.
% Temperature is in (K), pressure is in (Pa) and
% density is in (kg/m^3).
clear; clc;
zt=[0 1000 2000 3000 4000 5000];
Tt=[288.15 281.65 275.15 268.65 262.15 255.65];
pt=[10.133 8.9869 7.9485 7.0095 6.1624 5.4002]*1.0e+004;
rhot=[1.2252 1.1118 1.0065 0.9091 0.8191 0.7360];
fprintf('Enter the altitude at which atmospheric properties \n');
z=input('are to be determined. Altitude range is from 0 to 5000 m \n');
T=interp1(zt,Tt,z);
p=interp1(zt,pt,z);
rho=interp1(zt,rhot,z);
fprintf('T=%6.2f(K), p=%10.4e(Pa) rho=%6.4f(kg/m^3) \n',T,p,rho);
---------------------------------------------------------------------------
Program Results:
Enter the altitude at which atmospheric properties
are to be determined. Altitude range is from 0 to 5000 m.
1350
T=279.38(K), p=8.6235e+04(Pa) rho=1.0749(kg/m^3)
>>
The next example demonstrates the use of interp1 function for interpolat-
ing for internal energy of a refrigerant at temperatures specified in vector T2.
The output from interp1 will also be a vector.
Example 3.9
% Example_3_9.m
% This program uses MATLAB's function interp1 to interpolate for
% the internal energy, u, as a function of temperature, T, of
% an unspecified refrigerant.
% Measured values of u in (kJ/kg) vs. T in degrees (C)
% are specified in vectors ut and Tt respectively.
% The temperatures at which the internal energy is to be determined
% are specified in vector T2.
% The program also creates a plot of u vs. T and includes points of
% u at temperature T2.
clear; clc;
Tt=-20:10:90;
ut=[217.86 224.97 232.24 239.69 247.32 255.12 263.10 271.25 ...
279.58 288.08 296.75 305.58];
fprintf('This program interpolates for the internal energy, u at \n');
fprintf('a specified temperature T. \n');
Conditional Operators, Built-in Functions with Vector Arguments 95
Program Results:
This program interpolates for the internal energy, u at
a specified temperature T.
The allowable temperature range is -20 to +90 C.
T2(C) u(kJ/kg)
--------------------------
-12.0 223.548
6.0 236.710
24.0 250.440
32.0 256.716
64.0 282.980
82.0 298.516
>>
u vs. T
310
ut vs. Tt
300 u vs. T2
290
280
270
u(kJ/kg)
260
250
240
230
220
210
−20 0 20 40 60 80 100
T(C)
FIGURE 3.3
Internal energy, u, as a function of temperature, T, of an unspecified refrigerant.
96 MATLAB® Essentials
Z = 5 + [2 4 6 8] = [7 9 11 13]
Z = 5 ∗ [2 4 6 8] = [10 20 30 40]
C = A + B gives C = [( a1 + b1 ) ( a2 + b2 ) ( a3 + b3 )]
D = A − B gives D = [( a1 − b1 ) ( a2 − b2 ) ( a3 − b3 )]
a a2 a3 ,
D = A ./ B = 1
b1 b2 b3
= =
E A . ^ B [ a1b1 a2 b2 a3 b3 ] = power(A,B)
Example 3.10
To demonstrate the above relations, copy the following script and run the program
and observe the result.
% Example_3_10.m
% This program demonstrates some scalar and vector operations.
clear; clc;
s=5; a=[1 5 9]; b=[2 6 12]; c=s+a; d=s*b; e=a+b; f=a-b; g=a.*b;
h=a./b;
fprintf('s=%3i \n',s);
fprintf('a= %3i %3i %3i \n',a);
fprintf('\n');
fprintf('c=s+a\n');
fprintf('c= %3i %3i %3i \n',c);
fprintf('\n');
fprintf('s=%4i \n',s);
fprintf('b= %3i %3i %3i \n',b);
fprintf('d=s*b \n');
fprintf('d= %3i %3i %3i \n',d);
fprintf('\n');
fprintf('a= %3i %3i %3i \n',a);
fprintf('b= %3i %3i %3i \n',b);
fprintf('e=a+b \n');
fprintf('e= %3i %3i %3i \n',e);
fprintf('\n');
fprintf('a= %3i %3i %3i \n',a);
fprintf('b= %3i %3i %3i \n',b);
fprintf('f=a-b \n');
fprintf('f= %3i %3i %3i \n',f);
fprintf('\n');
fprintf('a= %3i %3i %3i \n',a);
fprintf('b= %3i %3i %3i \n',b);
fprintf('g=a.*b \n');
fprintf('g= %3i %3i %3i \n',g);
fprintf('\n');
fprintf('a= %3i %3i %3i \n',a);
fprintf('b= %4i %4i %4i \n',b);
fprintf('h=a./b \n');
fprintf('h= %8.4f %8.4f %8.4f \n',h);
fprintf('\n');
a=[2 3 4]; b=[2 2 2];
k=a.^b;
fprintf('a= %3i %3i %3i \n',a);
fprintf('b= %4i %4i %4i \n',b);
fprintf('k=a.^b \n');
fprintf('k= %4.1f %4.1f %4.1f \n',k(1),k(2),k(3));
--------------------------------------------------------------------------
Program Results:
s= 5
a= 1 5 9
c=s+a
c= 6 10 14
98 MATLAB® Essentials
s= 5
b= 2 6 12
d=s*b
d= 10 30 60
a= 1 5 9
b= 2 6 12
e=a+b
e= 3 11 21
a= 1 5 9
b= 2 6 12
f=a-b
f= -1 -1 -3
a= 1 5 9
b= 2 6 12
g=a.*b
g= 2 30 108
a= 1 5 9
b= 2 6 12
h=a./b
h= 0.5000 0.8333 0.7500
A= 2 3 4
B= 2 2 2
k=A.^B
k= 4.0 9.0 16.0
>>
--------------------------------------------------------------------------------
Example 3.11
% Example_3_11.m
% This example illustrates element-by element operation
% of two vector functions
clear; clc;
x = 0:30:180;
% y1 is the product of two vector functions
y1 = sind(x).* cosd(x);
fprintf(' x y1 y2 \n');
fprintf('---------------------------------------\n');
for n=1:length(x)
% y2(n) is the product of the elements of the two functions.
Conditional Operators, Built-in Functions with Vector Arguments 99
Program Results:
x y1 y2
-----------------------------------
0.0 0.00000 0.00000
30.0 0.43301 0.43301
60.0 0.43301 0.43301
90.0 0.00000 0.00000
120.0 -0.43301 -0.43301
150.0 -0.43301 -0.43301
180.0 -0.00000 -0.00000
>>
--------------------------------------------------------------------------------
We see that the two different methods for computing y1 and y2 give the
same answer.
REVIEW 3.2
Projects
P3.1. Though atmospheric conditions vary from day-to-day, it is convenient
for design purposes, to have a model for atmospheric properties with alti-
tude. The U.S. Standard Atmosphere, modified in 1976, is such a model. The
model consists of two types of regions, one in which the temperature varies
linearly with altitude, and the other is a region where the temperature is a
constant (see Figure P3.1).
100 MATLAB® Essentials
× 104 z versus T
8
Region 7
7
Region 6
6
5
Region 5
4
z
Region 4
3
Region 3
2
Region 2
1
Region 1
0
−80 −70 −60 −50 −40 −30 −20 −10 0 10 20
T
FIGURE P3.1
Temperature versus altitude of U.S. Standard Model Atmosphere.
gi
λ i ( zi +1 − zi ) λ i R
p = pi 1 − (P3.1)
Ti
T = Ti − λ i ( zi +1 − zi ) (P3.2)
where:
zi is the altitude at the beginning of region i, i = 1, 2, …, 7
zi+1 is the altitude at the end of region i and at the beginning of
region i+1
(pi , Ti) is the pressure and temperature at the beginning of region i
λ i is the lapse rate in region i
R is the air gas constant = 286.9 N − m kg − K
gi is the gravitational constant in region i. Although g varies
slightly with altitude we take g to be a constant in the region
evaluated at zi , otherwise the above expression for p would
be a lot more complicated than the one shown above
Conditional Operators, Built-in Functions with Vector Arguments 101
T = Ti (P3.3)
g ( z − zi )
p = pi exp − i (P3.4)
RTi
2z
g = go 1 − (P3.5)
Ro
where:
go = 9.810 m/s2
Ro = 6.3714e+6 m
z is the altitude at the beginning of the region
TABLE P3.1
U.S. Standard Atmosphere Property Table
Regional Properties of U.S. Standard Atmosphere
Region zi (km) Ti (K) p i (Pa) λ i (K/m) g i (m/s2)
0 288.15 101325 — 9.810
1 — — — 0.0065 —
11.0 — — — —
2 — — — 0.0000
20.0 — — — —
3 — — — −0.001 —
32.0 — — — —
4 — — — −0.0028 —
47.0 — — — —
5 — — — 0.0000 —
51.0 — — — —
6 — — — 0.0028 —
71.0 — — — —
7 — — — 0.0020 —
84.9 — — — —
102 MATLAB® Essentials
TABLE P3.2
Properties of Carbon Dioxide Based on
the Redlich–Kwong Equation of State
T (K) v (m3/kmol) p (bar)
350 0.28 7.65
400 0.32 8.57
450 0.36 9.16
500 0.40 9.55
550 0.44 9.81
600 0.48 10.00
650 0.52 10.14
700 0.56 10.24
750 0.60 10.31
Conditional Operators, Built-in Functions with Vector Arguments 103
TABLE P3.3
Refrigerant Properties
T (°C) v (m3/kg) u (kJ/kg)
−35 0.34235 244.33
−30 0.35369 217.58
−20 0.36513 222.43
−10 0.37649 227.37
−5 0.35778 232.42
0 0.39901 237.57
10 0.41019 242.82
20 0.42133 248.16
25 0.43243 253.61
30 0.44348 259.16
P3.4. The measured properties of a refrigerant are shown in Table P3.3. Create
a MATLAB program that will repeatedly ask the user if he/she wishes to
determine the refrigerant properties. If the answer is Y for yes, then ask
the user to enter a temperature at which the refrigerant properties are to
be determined. Use MATLAB’s interp1 function to evaluate the refrigerant
properties, and then print the result to the screen.
P3.5. This project involves the mass-spring-dashpot system (see Figure 2.19).
If the mass is displaced from its equilibrium position and released, the sub-
sequent motion of the mass will depend on the values of m, k, and c. To sim-
plify the writing of the governing equations, we will define
2
k c
arg = −
m 2m
ct
y = exp − (
× A cos ( arg t ) + B sin ( arg t )
2m
)
ct
y = exp − (
× A exp ( − arg t ) + B exp ( − − arg t )
2m
)
104 MATLAB® Essentials
where exp( x) = e x
We wish to consider four cases.
Create a MATLAB program that will plot the motion of y as a function of t for
0 ≤ t ≤ 20 s in steps of 0.1 s. To make the initial displacement equal to 0.5 m
and initial velocity equal to zero, use the following values for A and B.
For the case arg > 0, take
Ac
A = 0.5 m, B =
2 m arg
c c
0.5 − arg + − arg −
2 m ,B= A 2m
A=
2 − arg c
− arg +
2m
4
Self-Written Functions and MATLAB®’s
fminbnd Function
4.1 Introduction
In this chapter, we cover the self-written function, which is the last of the
building blocks that we mentioned earlier. Self-written functions are useful
if you have a complicated program and wish to break it down into smaller
segments. Also, if a series of statements is to be used many times, it is con-
venient to place them in a function. Many MATLAB® functions (such as
fminbnd, fzero, quad, and ode45) require a self-written function to define
the problem of interest. Self-written functions are equivalent to subroutines
in most programming languages, but in MATLAB they are usually stored in
separate files instead of the main program (though small functions can be
defined in the same file as your main script, as described in the section on
anonymous functions). The function file name must be saved as a .m file.
MATLAB has a function that determines the relative minimum or relative
maximum of a single variable function. The function is fminbnd and is
covered in this chapter. This MATLAB function requires the user to write a
self-written function, either as a separate .m file or as an anonymous func-
tion within the main script.
105
106 MATLAB® Essentials
FIGURE 4.1
MATLAB’s function template.
TABLE 4.1
Example Function Definitions
Function Definition Line Function File Name
function [p,T] = atm(z,rho) atm.m
function ex = exf (x) efx.m
function[] = output(x,y) output.m
The first executable statement in the function file must start with the word function.
Some example function definitions are shown in Table 4.1.
If the function has more than one output value, then the output variables
must be in brackets. If there is only one output value, then no brackets are
necessary. If there are no output values, use empty brackets.
In the next example, the input command is again used to ask the user
to enter an altitude from the keyboard. Earlier, it was mentioned that
MATLAB version R2016a has a bug. When the input command is exe-
cuted, the cursor remains in the Editor Window instead of moving to the
Command Window. So the user needs to click in the Command Window
before entering an altitude. This bug will be fixed in the next version of
MATLAB.
Program Results:
Enter the altitude at which atmospheric properties
are to be determined. Altitude range is from 0 to 5000 m
3400
z=3400.0(m), T=266.05(K), p=6.6707e+04(Pa), rho=0.8731(kg/m^3)
>>
-----------------------------------------------------------------------------------------------
We now want to modify Example 4.1, so that the input and output variables
to the function are vectors. We only need to modify Example 4.1, Part A. We
do not need to modify the function atm_fun.
The following example demonstrates that the names of the arguments in the
calling program need not be the same as those in the function. It is only
the order of the argument list in the calling program that needs to be in the
Self-Written Functions and MATLAB®’s fminbnd Function 109
same order as the argument list defined in the function. This feature is use-
ful when a function is to be used with several different scripts, each script
having different variable names, but each of the variables names correspond
to variables in the function. This concept is used in all of MATLAB’s built-in
functions.
Let us modify Example 4.2, Part A, and name it Example 4.3, Part A.
% atm_fun2.m
% This function works with Example 4.3, part A
function [A,B,C]=atm_fun2(x)
alt=[0 1000 2000 3000 4000 5000];
Temp=[288.15 281.65 275.15 268.65 262.15 255.65];
pres=[10.133 8.9869 7.9485 7.0095 6.1624 5.4002]*1.0e+004;
dens=[1.2252 1.1118 1.0065 0.9091 0.8191 0.7360];
A=interp1(alt,Temp,x);
B=interp1(alt,pres,x);
C=interp1(alt,dens,x);
fprintf('This output is from atm_fun2 \n');
fprintf(' x(m) A(K) B(Pa) C(kg/m^3) \n');
fprintf('------------------------------------------------\n');
for i=1:length(x)
fprintf('%6.1f %6.2f %10.4e %6.4f \n',...
x(i),A(i),B(i),C(i));
end
---------------------------------------------------------------------------
Program Results:
This output is from atm_fun2
x(m) A(K) B(Pa) C(kg/m^3)
------------------------------------------------
1250.0 280.02 8.7273e+04 1.0855
2560.0 271.51 7.4227e+04 0.9520
3480.0 265.53 6.6029e+04 0.8659
4360.0 259.81 5.8880e+04 0.7892
110 MATLAB® Essentials
Comparing results, we see that the names of the arguments in the calling program
need not be the same as those in the function. In the calling program, the names of the
input and output arguments are z, T, p, and rho. In the function, atm_fun2, the names
of the input and output arguments are x, A, B, and C. Looking at the results, we see
that x = z, A = T, B = p, and C = rho. It is only the order of the argument list in the
function that needs to be in the same order as the argument list in the calling program.
-------------------------------------------------------------------------------
fh = @(x,y)(y*sin(x)+x*cos(y));
In the above expression, MATLAB lists the @ sign as a function handle cre-
ation, fh is the function handle, the (x,y) defines the input arguments to
the function, and (y*sin(x)+x*(cos(y)) is the function. Anonymous
functions may be used in a script or in the Command Window.
Example: In the Command Window, type-in the following two lines:
>> fh = @(x,y)(y*sin(x)+x*cos(y));
>> w = fh(pi,2*pi)
w =
3.1416
-----------------------------------------------------------------------
Example 4.4
The following example uses an anonymous function that employs the interpola-
tion formula described in Equation 3.1. The script is a modification of Example 3.4
that contains atmospheric data of temperature, pressure, and density every
1000 meters. The script, interactively, asks the user to enter an altitude from the
keyboard.
% Example_4_4.m
% This program interpolates for atmospheric properties T, p and rho at
% an altitude entered from the keyboard.
% Atmospheric properties of temperature, pressure and density
% are specified every 1000 meters. The atmospheric properties at an
% altitude entered from the key board are determined by
% the interpolation formula described in Equation 3.1 and printed to
% the screen. An anonymous function, which avoids creating an extra .m
% file, is used to do the interpolation:
clear; clc;
% anonymous function
yf = @(z,z1,z2,y1,y2) (y1+(z-z1)*(y2-y1)/(z2-z1));
zt=[0 1000 2000 3000 4000 5000];
Tt=[288.15 281.65 275.15 268.65 262.15 255.65];
pt=[10.133 8.9869 7.9485 7.0095 6.1624 5.4002]*1.0e+004;
rhot=[1.2252 1.1118 1.0065 0.9091 0.8191 0.7360];
fprintf('Do you wish to have the atmospheric properties \n');
fprintf('at a specific altitude determined \n');
char=input('enter Y for yes or N for no \n','s');
if char=='N'
fprintf('Good Bye \n');
exit;
end
while char=='Y'
fprintf('Enter the altitude at which atmospheric properties \n');
fprintf('are to be determined. \n');
z=input('Altitude range is from 0 to 5000 m \n');
for i=1:length(zt)-1
if z >= zt(i) && z < zt(i+1)
z1=zt(i); z2=zt(i+1);
T1=Tt(i); T2=Tt(i+1);
T=yf(z,z1,z2,T1,T2);
p1=pt(i); p2=pt(i+1);
p=yf(z,z1,z2,p1,p2);
rho1=rhot(i); rho2=rhot(i+1);
rho=yf(z,z1,z2,rho1,rho2);
fprintf('z=%6.1f(m) T=%7.2f(C)',z,T);
fprintf('p=%12.5e(Pa) rho=%8.5f(kg/m^3) \n',p,rho);
end
end
fprintf('\n');
fprintf('Do you wish to enter another altitude ');
char=input('enter Y for yes or N for no \n','s');
if char=='N'
fprintf('Good Bye \n');
end
end
----------------------------------------------------------------------------
112 MATLAB® Essentials
Program Results:
Do you wish to determine atmospheric properties
at a specific altitude,
enter Y for yes or N for no
Y
Enter the altitude at which atmospheric properties
are to be determined.
Altitude range is from 0 to 5000 m
1480
z=1480.0(m) T= 278.53(C) p= 8.48847e+04(Pa) rho= 1.06126(kg/m^3)
REVIEW 4.1
1. When does it seem appropriate to write a self-written function?
2. In writing a self-written function what must be the first word
in the first executable statement?
3. A self-written function usually has both an input and an output.
Where does the input come from? Where does the output go to?
4. If a self-written function has more than one output, how must
the output be presented?
5. How does a self-written function communicate with the calling
program?
6. What can be said about variables in the self-written function
that are not in the input or output arguments of the function
and there are no global statements?
7. Do the variable names in the input and output arguments between
the calling program and the function have to be the same?
8. If a programmer wishes to write a self-written function, but
does not wish to create an additional .m file, what can the pro-
grammer do and what is the constraint?
Self-Written Functions and MATLAB®’s fminbnd Function 113
[x,FVAL] = fminbnd(FUN,x1,x2)
Example 4.5
Given: y( x ) = x 3 + 5.7 x 2 − 35.1x + 85.176.
Determine the relative minima and maxima.
% Example_4_5.m
% Find the minima and maxima of y = x^3 + 5.7x^2 – 35.1x + 85.176
clc; clear;
% First, plot the function so that we can determine the x range to use
% in fminbnd. Let us assume that the relative minimum lies between
% x1=-10, x2=6.
xf=-10:0.1:6;
y=xf.^3 + 5.7*xf.^2 − 135*xf + 85.176
plot(xf,y), xlabel('x'),ylabel('y'), grid, title('y vs x');
% Next, find the minimum and maximum using MATLAB's anonymous
% function method directly in the fminbnd function.
[xmin,ymin] = fminbnd( @(x) (x^3+5.7*x^2-35.1*x+85.176),-10,6 );
fprintf('xmin=%7.3f ymin=%9.3f \n',xmin,ymin)
% Note: To find a maximum, instead find the minimum of the
% negative of the function.
114 MATLAB® Essentials
Program Results:
xmin= 2.013 ymin= 45.774
xmax= -5.813 Ymax= 285.394
>>
y vs x
300
250
200
150
y
100
50
0
−10 −8 −6 −4 −2 0 2 4 6
x
FIGURE 4.2
Relative maximum and minimum of y versus x.
Self-Written Functions and MATLAB®’s fminbnd Function 115
Projects
P4.1. Before scientific calculators and computers existed, numerical values
for functions such as ln x, ex, cos x, and so on were given in tables. The table
values were determined by power series, such as a Maclaurin or a Taylor
series. For example, the cosine function can be represented by the following
series:
x2 x4 x6 xn
cos x = 1 − + − + ....... ..... valid for [ x 2 < ∞] (P4.1)
2! 4! 6! n!
P4.2. Repeat Project 4.1, but this time use the series expansion for the sine
function, which is
x x3 x5 xn
sin x = − + − + ..... .... valid for [ x 2 < ∞] (P4.2)
1! 3 ! 5 ! n!
where:
Cd is the discharge coefficient
ho is the fluid level in the tank at time, t = 0
Ao is the area of the orifice
AT is the cross-sectional area of the tank
1. Load the data file and create vectors Tt, vt, ut. Also create a vector,
T, that includes the temperatures at which the properties are to be
determined.
2. Call the self-written function using input variables of Tt, vt, ut, and
T and output variables T, v, and u.
3. Print to the Command Window a table consisting of T, v, and u with
table headings and units.
4. Plot vt versus Tt and on the same graph, plot v versus T as small x’s.
5. Plot ut versus Tt and on the same graph, plot u versus T as small x’s.
ρ V2 L
p1 − p2 = f (P4.6a)
2 D
where:
`ρ is the fluid density (kg/m 3 )
V is the average fluid velocity in the pipe (m/s)
Q = AV is the volume flow rate in the pipe (m 3/s )
D is the pipe diameter (m)
A is the pipe cross-sectional area = (πD2/4) (m2)
L is the pipe length between points 1 and 2 (m)
f is friction factor
118 MATLAB® Essentials
The friction factor has been determined by experiment. For smooth pipes a
formula that approximates the experimental data is [2]
where:
VD
Re = (Reynolds number) (P4.6c)
υ
m2 µ
υ is the fluid viscosity = (P4.6d)
s ρ
Develop a MATLAB program that contains both a calling program and a
function that determines the pressure drop, p1 − p2 versus the flow rate, Q. Q
is to vary from 0.001 to 0.02 m3/s in steps of 0.001 m3/s. Properties of D, L,
ρ , υ and Q are to be defined in the calling program. These values should be
made as an input argument to the function. The output from the function is to
be the pressure drop, p1 − p2, in the pipe and returned to the calling program.
In the calling program, a table of p1 − p2 versus Q is to be printed out to the
Command Window, including table headings and units. Use the following
values: ρ = 1000 kg m3, D = 0.16 m, L = 5 m and υ = 1.2 × 10 −6 m 2/s .
P4.7. This project is a modification of Project P3.5. That project involved the
mass motion in a mass-spring-dashpot system. A sketch of such a system is
shown in Figure 2.19. Disturbing the mass position, y, from its equilibrium
position and releasing it with zero velocity, will result in the y position vary-
ing with time, t.
As discussed in Project P3.5, the type of motion that the mass will have
depends on the values of the system properties of m, k, and c, where m is the
mass, k is the spring constant, and c is the damping factor [3].
If, (k/m) > (c/2 m)2 , then the mass motion will be damped oscillations and
the governing equation describing the motion is
2 2
c k c k c
y = exp − t A cos − t + B sin − t (P4.7a)
2m m 2 m m 2 m
Ac
A = 0.5 m, B =
2 m arg
If, k /m < (c/2m)2 , then the mass motion will be damped exponential
motion and the governing equation will be
c
c
2
k
c
2
k
y = exp − t A exp − t + B exp − − t (P4.7b)
2 m 2m m 2m m
c c
0.5 − arg + − arg −
2m 2 m
A= ,B= A
2 − arg c
− arg +
2m
If (c/2 m)2 = k/m, then the system is critically damped. For this case, the
solution is
c
y = ( A + Bt)exp − t (P4.7c)
2m
c
A = 0.5 m, B = A
2m
Case 1
N N−s
m = 75 kg , k = 85 , c = 200
m m
Case 2
N N−s
m = 80 kg , k = 150 , c = 40
m m
120 MATLAB® Essentials
Case 3
N N−s
m = 50 kg , k = 50 , c = 100
m m
Case 4
N N−s
m = 100 kg , k = 200 , c = 20
m m
P4.8. Mathematician Joseph Fourier is credited with the theorem that any
periodic waveform may be expressed as a summation of pure sines and
cosines [4]. For example, the square wave of Figure P4.1a can be written as a
sum of sine terms:
v
−1
T = 1 ms
(a)
v 1st term
(b)
FIGURE P4.1
(a) Square wave and (b) using 1st, 2nd, and 3rd terms in the series and their sum.
Self-Written Functions and MATLAB®’s fminbnd Function 121
4 2π t 4 6π t 4 10π t
v(t) = sin + sin + sin +
π T 3π T 5π T
∞
(P4.8)
2π k t
∑
4
= sin
k =1
πk T
k odd
Figure P4.1b shows the first three terms of the series and their summation.
P4.9. This project is a modification of Project P4.7. That project involved the
mass motion in a mass-spring-dashpot system. A sketch of such a system is
shown in Figure 2.19. Disturbing the mass position, y, from its equilibrium
position and releasing it with zero velocity, will result in the y position varying
with time, t. In this project we will consider the case k /m > ( c/2m ) , result-
2
ing in the mass motion being damped oscillations. The governing equation
describing the motion is
2 2
c k c k c
y = exp − t A cos − t + B sin − t (P4.7a)
2m m 2 m m 2 m
where:
2
k c
arg = −
m 2m
x = Vo cos(ϑo ) t (2.5)
g 2
y = Vo sin(ϑo ) t + t (2.6)
2
Take the (x, y) position of the center of the hoop to be (xf , yf) = (8.0 m, 3.048 m),
ϑo = 45°, Vo = 9.5169 m, and time of flight, tf = 1.1888 s.
-----------------------------------------------------------------------
References
1. Bober, W., Introduction to Numerical and Analytical Methods with MATLAB for
Engineers and Scientist, CRC Press, Boca Raton, FL, 2014.
2. Bober, W., The use of the Swamee-Jain formula in pipe network problems,
Journal of Pipelines, 4, 315–317, 1984.
3. Thomson, W. T., Theory of Vibration with Applications, Prentice Hall, Englewood
Cliffs, NJ, 1972.
4. Bober, W., Stevens, A., Numerical and Analytical Methods with MATLAB for
Electrical Engineers, CRC Press, Boca Raton, FL, 2012.
5
Working with Characters and Strings
5.1 Introduction
There may be a time that you might wish to create a matrix consisting of a
string of characters and to print it out in a report. This chapter shows you
how to do that. In MATLAB®, characters and strings usually need to be
enclosed by single quotation marks.
Example 5.1
% Example_5_1.m
% This program demonstrates how to print out rows of character
% strings. This can be done by declaring a column vector where each
% element in the vector is a character string.
% Note that all row character strings must have the same number
% of columns and be enclosed by single quotation marks.
clear; clc;
% Assign a string column vector.
% Each row in the column vector must have the same number of columns.
parts=['Internal modem '
'Graphics adapter '
'CD drive '
'DVD drive '
'Floppy drive '
'Hard disk drive '];
for i=1:6
fprintf('%16s \n',parts(i,1:16));
end
----------------------------------------------------------------------------------------
Program Results:
Internal modem
Graphics adapter
CD drive
DVD drive
Floppy drive
Hard disk drive
>>
-----------------------------------------------------------------------
123
124 MATLAB® Essentials
Example 5.2
This example is an interactive program. The user has to input whether to print the
string matrix to the screen or to a file.
% Example_5_2.m
% This example is a modification of Example 5.1.
% The program asks the user if he/she wishes to have the
% output go to the screen or to a file.
% This example also illustrates the use of the switch statement.
clear; clc;
parts=['Internal modem '
'External modem '
'Graphics circuit board '
'CD drive '
'Hard disk drive '];
fprintf('Choose whether to send the output to the\n');
fprintf('screen or to a file named output.txt. \n\n');
var=input('Enter S for screen or F for file (without quotes)\n','s');
switch(var)
case 'S'
for i=1:5
fprintf('%22s \n',parts(i,1:22));
end
case 'F'
fo=fopen('output.txt','w');
for i=1:5
fprintf(fo,'%22s \n',parts(i,1:22));
end
fclose(fo);
otherwise
fprintf('you did not enter an S or a F, try again \n');
exit;
end
---------------------------------------------------------------------------------
Program Results:
Choose whether to send the output to the
screen or to a file named 'output.txt'.
Enter S for screen or F for file (without single quotes)
S
Internal modem
External modem
Graphics circuit board
CD drive
Hard disk drive
>>
--------------------------------------------------------------------------------
Working with Characters and Strings 125
Example 5.3
In this interactive example, we illustrate the use of the if-elseif ladder to establish
a letter grade when the user enters a numerical score.
% Example_5_3.m
% This example uses the if-elseif ladder.
% The program determines a letter grade depending on the score the user
% enters from the keyboard.
clear; clc;
gradearray=['A'; 'B'; 'C'; 'D'; 'F'];
score=input('Enter your test score: \n');
fprintf('score is: %i \n',score);
if score > 100
fprintf('error: score is out of range. Rerun program \n');
break;
elseif score >= 90 && score <= 100
grade=gradearray(1);
elseif score >= 80 && score < 90
grade=gradearray(2);
elseif score >= 70 && score < 80
grade=gradearray(3);
elseif score >= 60 && score < 70
grade=gradearray(4);
elseif score < 60
grade=gradearray(5);
end
fprintf('grade is: %c \n',grade);
---------------------------------------------------------------------------------
Program Results:
Enter your test score: 76
score is: 76
grade is: C
>>
--------------------------------------------------------------------------------
Example 5.4
This example is a modification of Example 5.3. In this interactive example a for loop
is used to establish the interval containing the grade.
% Example_5_4.m
% The program determines a letter grade depending on the score the user
% enters from the keyboard.
% This version uses a loop to determine the correct interval of
126 MATLAB® Essentials
Program Results:
Enter your test score: 82
score is: 82
grade is: B
>>
---------------------------------------------------------------------------
Example 5.5
This example combines the use of a string matrix and the establishment of a grade.
% Example_5_5.m
% This program determines the letter grades of several students.
% Student's names and their test scores are entered in the program.
% Student names are not connected to real people.
% This example uses nested 'for' loops and an 'if' statement
% to determine the correct letter grade for each student.
clear; clc;
gradearray=['A'; 'B'; 'C'; 'D'; 'F'];
sarray=[100 90 80 70 60 0];
Lname=['Smith '
'Lambert '
'Kurtz '
'Jones '
'Hutchinson'
'Blake '];
Fname=['Joe '
'Jane '
'Howard '
'Mary '
'Peter '
'Henry '];
score=[84; 86; 67; 92; 81; 75];
Working with Characters and Strings 127
avg_score=mean(score);
fprintf('The group average numerical grade is:%4.1f \n',avg_score);
% Index j selects the student and index i selects the letter grade.
% The score = 100 is treated separately.
for j=1:6
if score(j) == 100
grade(j)=gradearray(1);
else
for i=1:5
if score(j) >= sarray(i+1) && score(j) < sarray(i)
grade(j)=gradearray(i);
end
end
end
end
fprintf('Last name First name grade \n');
fprintf('--------------------------------------\n');
for j=1:6
fprintf('%12s %10s %c \n',
Lname(j,1:12), Fname(j,1:10), grade(j));
end
--------------------------------------------------------------------------
Program Results:
The group average numerical grade is:80.8
Last name First name grade
--------------------------------------
Smith Joe B
Lambert Jane B
Kurtz Howard D
Jones Mary A
Hutchinson Peter B
Blake Henry C
>>
---------------------------------------------------------------------------
The function will read data from an open text file identified by fo into a cell
array C. The format is of the form %f, %d, %c, %s, and so on. The number of
format specifiers determines the number of cells in the cell array C. Each cell
will contain the number of lines contained in the data file and be of the type
128 MATLAB® Essentials
specified by the format statement. String specifiers also include %q, which
is a string enclosed by double quotation marks. In the textscan statement,
the format for a string of n characters is %nc, but in the print statement, the
format for a string of n characters is %ns.
NOTE: To reference the contents of a cell, enclose the cell number with {}. See
the following example:
If you wish to read in N lines from the open data file, use
C = textscan('fo', format,N)
Example 5.6
Loads mixed text and numerical data from a file
% Example_5_6.m
% Load the product data from inv4.txt into the arrays 'cat_nu', 'desc',
% 'cost', and print the results to the screen.
clear; clc;
fo=fopen('inv4.txt'); % Note: inv4.txt is defined below.
C = textscan(fo,'%d %14c %f',5);
% Contents of cell block C contains 5 rows and 3 columns
cat_nu = C{1};
desc = C{2};
cost = C{3};
fclose(fo);
fprintf('catalog # description \t\t cost \n');
fprintf('---------------------------------------\n');
for i=1:5
fprintf('%5i \t %14s \t %6.2f \n\n',...
cat_nu(i),desc(i,1:14),cost(i));
end
-----------------------------------------------------------------------
% inv4.txt file (do not include this line in your data file)
1001 hammer 2.58
1002 plier 1.20
1003 screwdriver 1.56
1004 soldering iron 3.70
1005 wrench 2.60
---------------------------------------------------------------------------------
Program Results:
catalog # description cost
---------------------------------------
1001 hammer 2.58
1002 plier 1.20
1003 screwdriver 1.56
1004 soldering iron 3.70
1005 wrench 2.60
>>
---------------------------------------------------------------------------------
Working with Characters and Strings 129
REVIEW 5.1
Projects
P5.1. Create a MATLAB program that
1. Contains a string array that lists the names of five courses that you
have taken recently.
2. Contains a vector of the numerical grades received in each of the five
courses.
3. Prints to the screen the names of the five courses and their grades.
4. Prints to the screen the average grade received in the five courses.
P5.2. You are a student adviser and you wish to have the user (student)
tell you the grades that he/she received on several courses. You are to use
MATLAB’s input command to ask the student to enter the grade that he
received in the course.
Create a MATLAB program that
P5.3. Create a MATLAB program that creates a vector listing all the days of
the week, that is, Monday, Tuesday, and so on. Create a second vector that
describes two activities that you wish to do on each day of the week, such as
130 MATLAB® Essentials
Attend calculus class and have dinner with girl or boy friend, and so on. Do this
for each day of the week. Use an input statement to have the user enter the
day of the week. Based on that entry and using a Switch Statement print out
the activities of that day listed in the second vector.
P5.4. Bob’s Hardware Store wishes to create an online program to sell inven-
tory items in its store. You are to create an interactive MATLAB program for
this purpose. The program is to contain a data file, a main program and a
billing function.
Data file:
The data file is to contain a catalog number and a description of the
inventory items for sale, their costs, and the quantity available for
sale. The list should contain at least 10 items. The data file is to be
loaded into the main script.
Main script:
1. The script is to print to the screen the items for sale, including their
catalog numbers and descriptions, their cost, and the quantity
available for purchase.
2. The script is to ask the user if he/she wishes to make a purchase. If
no, exit the program. If yes, the script is to ask the user for his/her
first and last name. It should then ask the user the catalog number of
the item he/she wishes to purchase and the quantity.
3. The script is to continue asking the user if he/she wishes to make
another purchase. If the response is no, call the billing function and
exit the program. If the response is yes, print to the screen the list
of items, their cost, and the updated items available for purchase.
Then, the script is to ask the user the catalog number of the item
he/she wishes to purchase and the quantity.
4. Billing function:
Input arguments:
First and last names of the purchaser, the number of items purchased,
the catalog numbers, their costs, the quantities of the items purchased.
Output arguments:
None, use open and closed brackets.
Use a global statement for the description of the items purchased
(both in the calling program and in the billing function). The bill
should contain the name and address of the store, the customer’s
first and last names, bill headings, the catalog numbers of all the
items purchased, their unit prices, the total price for each item pur-
chased, and finally the total price of all the items purchased.
Clear the screen, then print the bill to the screen.
6
Roots of Algebraic and
Transcendental Equations
6.1 Introduction
In the analysis of various engineering problems, we are often faced with a
need to find roots of equations whose solution is not easily found analyti-
cally. Given a function f(x), the roots of the function are the values of x that
makes f(x) = 0. For example, the equation
f ( x) = ax 2 + bx + c = 0 (6.1)
where a, b, and c are constants, is an equation that we are all familiar with.
The values of x that satisfy the equation are the roots of f(x). We even have a
formula for the roots, which are
−b ± b 2 − 4 a c
x= (6.2)
2a
−b + b 2 − 4 a c −b − b 2 − 4 a c
x1 = , x2 = (6.3)
2a 2a
131
132 MATLAB® Essentials
x1 , x2 , x3 , xN +1 with xi +1 = xi + ∆x
The sign change usually indicates that a real root has been passed. However,
it may also indicate a discontinuity in the function. (Example: tan x is
discontinuous at x = π 2.)
A brief description of the Bisection method follows:
f (x)
f (x3) f (x4)
x1 x2
x
x3 x4 ... xN xN+1
f (x2)
f (x1)
FIGURE 6.1
The root of f(x) lies between x2 and x3.
Roots of Algebraic and Transcendental Equations 133
For cases 1 and 2, select the interval containing the root and repeat the pro-
cess. Continue repeating the process, say r times, then (∆x) f = ∆x 2 r , where
∆x is the initial size of the interval containing the root before the start of the
bisection process (∆x = xi +1 − xi ) and (∆x) f is the size of the interval contain-
ing the root after r bisections. If (∆ x) f is sufficiently small, then a very good
approximation for the root is anywhere within the last bisected interval, say
the midpoint of the interval. For example, in 20 bisections,
∆x
(∆x) f = ≈ ∆x × 1.0 × 10 −6
2 20
---------------------------------------------------------------
f (x)
x
xi xi+½ xi+1
FIGURE 6.2
Bisecting the interval containing the root.
134 MATLAB® Essentials
Example 6.1
Given the equation
3.3 0.325
f(v) = − −2 (6.6)
v − 0.03 v(v + 0.03)
% Example_6_1.m
% Simple use of fzero function
% Find the root of f(v)=3.3/(v-0.03)-0.325/(v(v+0.03))-2
% Guess that the root lies between 1 and 2.
% Function name is fv and the function is a .m file.
clear; clc;
v=1.0:0.1:2.0;
for j=1:length(v)
f(j)=fv(v(j));
end
plot(v,f), xlabel('v'), ylabel('f'), title('f vs. v'), grid;
root=fzero('fv',1.6);
% Note: we could also have used root=fzero(@fv,1.6)
fprintf('root=%6.4f \n',root);
froot=fv(root);
fprintf('froot=%12.4e \n',froot);
----------------------------------------------------------------------------
% This function works with Example 6.1
function f=fv(v)
f=3.3/(v-0.03)-0.325/(v*(v+0.03))-2;
------------------------------------------------------------------------------
Program Results:
root= 1.5810
froot= 0.0000e+00
>>
See Figure 6.3.
-----------------------------------------------------------------------
Roots of Algebraic and Transcendental Equations 135
f vs. v
1.2
0.8
0.6
0.4
f
0.2
−0.2
−0.4
−0.6
1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2
v
FIGURE 6.3
Plot of f versus v.
Example 6.2
In the next two examples, we will determine the root of Equation 6.5 by placing
an anonymous function directly into the fzero function and also as by placing
an anonymous function in the main script. In both cases no separate .m file is
used.
% Example_6_2.m
% Anonymous function applied directly into the fzero function
% Find the root of f(v)=3.3/(v-0.03)-0.325/(v(v+0.03))-2
% Guess that the root lies between 1 and 2.
clear; clc;
root=fzero(@(v) (3.3/(v-0.03)-0.325/(v*(v+0.03))-2),1.6);
fprintf('root=%6.4f \n',root);
froot=fv(root);
fprintf('froot=%12.4e \n',froot);
-------------------------------------------------------------------------
Program Results:
root= 1.5810
froot= 0.0000e+00
>>
------------------------------------------------------------------------
% Example_6_3.m
% Anonymous function used with the fzero function.
% Find the root of f(v)=3.3/(v-0.03)-0.325/(v(v+0.03))-2
136 MATLAB® Essentials
Program Results:
The results are exactly the same that was obtained in Example 6.1.
------------------------------------------------------------------------
In some instances, we would like to find the zero of a function of two argu-
ments, say X and P, where P is a parameter and is fixed. In order to solve
with fzero, P must be defined in the calling program. For example, suppose
myfun is defined in a .m file as a function of two arguments:
function f = myfun(X,P)
f = cos(P*X);
P = 1000;
root = fzero(@(X) myfun(X,P),X0)
where root is the zero of function myfun when P=1000. Note that P needs
to be defined before the fzero function is called.
An alternative to adding parameter P as an argument in myfun is to use
MATLAB’s global statement. The parameter P should be defined in the call-
ing program and be listed as a variable in the global statement. The global
statement needs to be used in both the calling program and in the function
myfun and be exactly the same in both scripts. See the following example.
Example
Calling program:
global P;
P=1000;
Xo=10.0;
root = fzero(@myfun,Xo);
-------------------------------------------------------------------------
Roots of Algebraic and Transcendental Equations 137
Now, let us consider the case when there is more than one root in the function
under consideration. First, it is best to use the search method to obtain small
intervals in which the roots lie. For each obtained interval define the argu-
ment X0 in the fzero command (see Equation 6.5) as a vector of length two;
that is, X0(1) is the X position at the beginning of one of the found intervals
and X0(2) is the X position at the end of that interval. This should result in
the sign of FUN(X0(1)) to differ from the sign of FUN(X0(2)). If that is
not the case, MATLAB will return an error message. The following example
illustrates this concept:
Example 6.4
The position, y, of a mass in a mass-spring-dashpot system (see Figure 2.19) that is
underdamped is given by
k 2 k 2
c c c
y = exp − t A cos − t + B sin − t (6.7)
2m m 2m m 2m
Determine the number of roots, their values and y values at the obtained roots for
0 ≤ t ≤ 10 s. Take
m = 25.0 kg, c = 5.0 N-s/m, k = 200.0 N/m, A = 0.2 m, and
c A
B= ×
2m k/m − (c/2m)2
% Example_6_4.m
% This program determines the number of roots and their values
% in the mass-spring-dashpot system in the time span 0<=t<=10 s.
% The governing equation for the displacement, y(t), of the
% under-damped vibration problem is:
% y(t)=exp(-c*t/2/m)(A*cos(arg1*t)+B*sin(arg1*t)), where
% arg1=sqrt(k/m-(c/2/m)^2)
% k=200 N/m, m=25kg, c=5 N-s/m
% A=0.2m, B=c/(2*m)*A/arg1.
% The values for constants A and B represent an initial
% displacement of the mass from its equilibrium position
% at zero velocity.
% A global statement in used to bring the constants, k, m, c,
% A, B and arg1 into the function fun_spring.
clear; clc;
global m k c A B arg1;
m=25; k=200; c=5; A=0.2;
arg1=sqrt(k/m-(c/2/m)^2);
B=c/2/m*A/arg1;
138 MATLAB® Essentials
Program Results:
root # root(s) y(root)(m)
-----------------------------------------
1 0.568218 -1.3111e-17
2 1.679634 -1.2099e-16
3 2.791049 -7.2174e-18
4 3.902465 1.0979e-16
5 5.013881 -2.9893e-16
6 6.125296 6.1582e-17
7 7.236712 -4.2906e-17
8 8.348127 2.8230e-17
9 9.459543 -1.5493e-17
>>
See Figure 6.4.
---------------------------------------------------------------------------
Roots of Algebraic and Transcendental Equations 139
0.15
0.1
0.05
y(m)
−0.05
−0.1
−0.15
−0.2
0 1 2 3 4 5 6 7 8 9 10
t(s)
FIGURE 6.4
Plot of mass motion in a mass-spring-dashpot system.
Example 6.5
In this example, MATLAB’s roots function is used to find the roots of a polynomial.
% Example_6_5.m
% This program determines the roots of two different polynomials
% using MATLAB’s 'roots' function.
clear; clc;
% The first polynomial is: f=x^3-5.7*x^2-35.1*x+85.176. The
% roots of this polynomial are all real.
% Define coefficients of first polynomial (real roots)
fprintf('The coefficients of the first polynomial are: \n');
C=[1.0 -5.7 -35.1 85.176]
fprintf('The roots are: \n');
V=roots(C)
fprintf('Polynomial coefficients determined from poly(V) are:\n');
C_recalc=poly(V)
fprintf('----------------------------------------\n');
% The second polynomial is: f=x^3-9*x^2+23*x-65. The roots of
% this polynomial are both real and complex. Complex roots must
% be complex conjugates.
% Define the coefficients of second polynomial
fprintf('The coefficients of the second polynomial are \n');
D=[1.0 -9.0 23.0 -65.0]
fprintf('The roots are: \n');
W=roots(D)
fprintf('The real and imaginary parts of the roots are:\n');
re=real(W)
im=imag(W)
fprintf('Polynomial coefficients determined from poly(W) are:\n');
W_recalc = poly(W)
----------------------------------------------------------------------
Program Results:
The coefficients of the first polynomial are:
C =
1.0000 -5.7000 -35.1000 85.1760
The roots are:
V =
8.6247
-4.9285
2.0038
Polynomial coefficients determined from poly(V) are:
C_recalc =
1.0000 -5.7000 -35.1000 85.1760
-------------------------------------------------------------------------
The coefficients of the second polynomial are
D =
1 -9 23 -65
The roots are:
W =
7.0449 + 0.0000i
Roots of Algebraic and Transcendental Equations 141
0.9775 + 2.8759i
0.9775 - 2.8759i
The real and imaginary parts of the roots are:
re =
7.0449
0.9775
0.9775
im =
0
2.8759
-2.8759
Polynomial coefficients determined from poly(W) are:
W_recalc =
1.0000 -9.0000 23.0000 -65.0000
>>
------------------------------------------------------------------------------
REVIEW 6.1
Projects
P6.1. This project is a variation of Project P2.1. In that project a tennis
player on serve places the tennis ball close to the outside line of the service
box when the ball hits the ground (see Figure P6.1a and b). The horizon-
tal distance from the point where the ball leaves the racket to where the
ball hits the ground is 18.925 m. The horizontal distance from the point
where the ball leaves the racket to where the net is located is 12.509 m.
The vertical distance above the ground when the ball leaves the racket
is yo = 2.438 m. The speed of the ball as it leaves the racket is 58.0 m/s.
Determine the angle, ϑo , that the ball makes with the horizontal on leav-
ing the players racket that would result in the ball hitting the ground at
the position stated. Neglecting drag, the governing equations describing
the motion are
x = Vo cos(ϑo ) t (P6.1a)
g
y = − t 2 − Vo sin(ϑo ) t + yo (P6.1b)
2
Hint: Let ( x f , y f ) be the position and t f be the time when the ball hits
the ground. Substitute these values in Equations P6.1a and P6.2a, then
solve for t f in the modified Equation P6.1a and substitute the obtained
expression into the modified Equation P6.1b. This gives a transcendental
Ball path
Ball leaves
racket
Net
(a)
y
Ball leaves racket
FIGURE P6.1
(a) Tennis court layout. (b) Path of tennis ball after it leaves the racket.
Roots of Algebraic and Transcendental Equations 143
x = Vo cos(ϑo ) t (P6.2a)
g 2
y= t + Vo sin(ϑo )t + yo (P6.2b)
2
Take the (x, y) position of the center of the hoop to be (xf , yf ) = (6.0 m, 3.048 m)
and yo = 1.98 m.
1. Determine the angle ϑo that will result in the ball reaching the center
of the hoop at time tf .
2. Determine the time, tf , that it takes for the ball to reach the center
of the hoop. Time, t, equals zero when the ball leaves the player’s
hands.
3. Create a table consisting of t, x, y for 0 ≤ t ≤ t f in steps of t f 10. Carry
variables to four decimal places. Print the table to an output file,
including tf and ϑo.
4. Create a plot of y versus x.
TABLE P6.1
Values of a, b and, R for Carbon Dioxide in Redlich–Kwong’s Equation of State
N- m4 - K1/ 2 m3 Nm
a 2 b R
Gas kmol kmol K- kmol
Source: Moran, M. J. and Shapiro, H. N., Fundamentals of Thermodynamics, John Wiley & Sons,
Hoboken, NJ, 2004.
Write a MATLAB program utilizing the fzero function to calculate the spe-
cific volume by Redlich–Kwong’s equation. Use the value of v obtained from
the ideal gas law as your guess for the root in MATLAB’s fzero function.
Construct a table as shown in Table P6.2.
Roots of Algebraic and Transcendental Equations 145
TABLE P6.2
v Determined by Redlich–Kwong Equation and by Ideal Gas Law for Carbon Dioxide
Ideal Gas Redlich–Kwong Equation
T(K) v (m3/kmol) v (m3/kmol) % Error in v
350 --------- ---------- ---------
400 --------- ---------- ---------
----- --------- ---------- ---------
----- --------- ---------- ---------
700 --------- ---------- ---------
P6.4. Determine the first root of the voltage, v(t), of the underdamped parallel
RLC circuit described in Project P2.7. The governing equation for v(t) is
1 2 1 2
1 1 1
v(t) = exp − t A cos − t + B sin − t (P6.4)
2RC LC 2RC LC 2RC
Use MATLAB’s fzero function to find the first root. Print this value to the
screen. Also plot v versus t. Assume the following parameters:
TABLE P6.3
Van der Waals’ Constants
N m4 m3 Nm
a 2 b R
Gas # Gas kmol kmol K kmol
Source: Moran, M. J. and Shapiro, H. N., Fundamentals of Thermodynamics, John Wiley & Sons,
Hoboken, NJ, 2004.
146 MATLAB® Essentials
x 2 2
∞ sin(δn )cos δn e − aδn t/L
T ( x , t) = T∞ + 2(T0 − T∞ ) ∑
n=1
L
cos(δn )sin(δn ) + δn
(P6.6a)
where:
L = 1/2 of the plate thickness
a is the the thermal diffusivity of the plate material
δn are the roots of the equation:
hL
F(δ) = tan δ − =0 (P6.6b)
kδ
where:
h is the convective heat transfer coefficient for the bath
k is the thermal conductivity of the plate material
There are an infinite number of roots to Equation P6.5b. This can be seen in
Figure P6.2b. The roots being δ1, δ2 , δ3 , …, δn. Note that δ1 lies between 0 and π/2,
δ2 lies between π and 3π/2, δ3 lies between 2π and 5π/2, and so on. Subtracting
T∞ from Equation P6.6a and dividing by T0 − T∞ , we obtain Equation P6.6c:
x x − aδn2t/L2
T , t − T∞ ∞ sin(δn )cos δn e
TRATIO =
L
T0 − T∞
=2
n=1
∑ L
cos(δn )sin(δn ) + δn
(P6.6c)
A plot of TRATIO versus time, for several different values of x/L should
appear as shown in Figure P6.2c.
Finally, the heat transfer ratio, Qratio, from the plate to the bath in time t is
given by
∞
∑ δ [sin δ cos δ
Q(t) 2hL sin δn cos δn 2 2
QRATIO = = 1 − e − at δ n /L (P6.6d)
n + δn ]
2
Q0 k n =1 n n
where:
Q(t) is the amount of heat transferred from the plate to the bath in time t.
Q0 is the amount of heat transferred from the plate to the bath in infinite time,
which equals the change in internal energy in infinite time.
1. Write a computer program that will solve for the roots, δ1, δ2, . . . . , δ50
using MATLAB’s fzero function. Print out the δ values in 10 rows and
5 columns. Also print out the functional values at the roots, that is, f(δn).
NO T E : Only 50 δ values were asked to be computed.
Roots of Algebraic and Transcendental Equations 147
Bath at Bath at
temperature T∞ Plate temperature T∞
(a) x
tan δ, hL/kδ
tanδ
hL
kδ
(b)
TRATIO
1.0
x/L = 0.0
x/L = 0.2
x/L = 0.4
x/L = 0.6
x/L = 1.0
t
(c) 0
FIGURE P6.2
hL
(a) Plate cooling in a bath. (b) Plot of tan δ and versus δ. (c) Plot of TRATIO versus t.
kδ
2. Solve Equation P6.6c for TRATIO for x/L = 0.0, 0.2, 0.4, 0.6, 0.8, 1.0
and t = 0, 10, 20, … 200 s. Print out results in table form as shown
in Table P6.4. Also use MATLAB to produce a plot similar to
Figure P6.2c.
148 MATLAB® Essentials
TABLE P6.4
Temperature Ratio, TRATIO
X/L
Time(s) 0.0 0.2 0.4 0.6 0.8 1.0
3. Construct a table for QRATIO versus t for times 0, 10, 20, 30, . . . . , 200 s.
4. Use MATLAB to produce a plot of QRATIO versus t.
h 2 αt
h αt Ts − Ti
1− e k2
1 − erf − =0 (P6.7)
k T∞ − Ti
FIGURE P6.3
Ice slab subjected to warm front.
Roots of Algebraic and Transcendental Equations 149
Given: Ti = −20°C, T∞ = 20˚C, k = 2.22 W/m-C, α = 12.6 × 10−7 m2/s, and h = 100
W/m2-C. We wish to determine the time, t, when the surface temperature of
the slab reaches the following temperatures:
T = [−10 −5 0]°C
Use the search method to find an interval in which the root of Equation P6.7
lies. Then use MATLAB’s fzero function to solve for the time, t, for each
condition and print the results in a table with table headings. Assume that
0 ≤ t ≤ 1000 s with a step size of 10 s.
y
x(y) = ±√R2 − y2
x
d
dy
2x(y)
FIGURE P6.4
Floating wood circular cylinder.
150 MATLAB® Essentials
3. Uses MATLAB’s fzero function to obtain a better value for the root.
4. Create a table consisting of S and d (include table headings) and a
plot of d versus S.
P6.10. In the time span 0 ≤ t ≤ 0.5 ms, determine the number of roots and
their values of the voltage, v(t), of the underdamped parallel RLC circuit
described in Project 2.8. The governing equation for v(t) is
1 2 1 2
1 1 1
v(t) = exp − t A cos − t + B sin − t (P6.10)
2RC LC 2RC LC 2RC
1. Use the search method to find a small interval in which each root lies.
2. In each found interval, use MATLAB’s fzero function to find the
root value.
3. Print out to the screen, the root number and the root value.
qv D
Vin − IS e kT − 1 RD − vD = 0 (P6.11a)
iR
+
+ R vR
Vin −
− +
iD vD
−
FIGURE P6.5
Semiconductor for PN diode.
Let
qv D
f (vD ) = Vin − IS e kT − 1 R − vD = 0 (P6.11b)
1. Create a MATLAB function for f (vD ) and plot for the interval
0 ≤ vD ≤ 0.8 V for 10 mV steps (80 subdivisions on the vD domain).
2. Use the search method to obtain a small interval within which the
root of Equation P6.11b lies.
3. Use MATLAB’s fzero function to obtain a more accurate value for
the root. Use the following parameters:
T = 300 K, I s = 10 −14 A, Vin = 5 V, R = 1000 Ω .
P6.12. We wish to determine the DC transfer characteristic for the diode cir-
cuit of Figure P6.5. We will consider Vin as a parameter, where 5 ≤ Vin ≤ 12 in
steps of 1 V. We wish to find the value of vD for all values of Vin .
Write a MATLAB program that will find the roots of f (vD ) = 0, where
qv
D
f (vD ) = Vin − IS e kT − 1 R − vD = 0 (P6.12)
References
1. Moran, M. J. and Shapiro, H. N., Fundamentals of Thermodynamics, John Wiley &
Sons, Hoboken, NJ, 2004.
2. Bober, W., Introduction to Numerical and Analytical Methods with MATLAB for
Engineers and Scientists, CRC Press, Boca Raton, FL, 2014.
3. Bober, W. and Stevens, A., Numerical and Analytical Methods with MATLAB for
Electrical Engineers, CRC Press, Boca Raton, FL, 2013.
7
System of Algebraic, Linear Equations
7.1 Introduction
In engineering we are frequently confronted with dealing with a problem
involving a set of algebraic, linear equations. In this chapter we discuss the
use of MATLAB® ’s inv and Gauss-Elimination functions for solving a
system of algebraic, linear equations.
Before the use of computers, the method of determinants was used to
obtain a solution to a system of algebraic, linear equations. Computationally,
it is only practical for a system involving just a few equations [1]. Since it is
much easier to solve such a system by MATLAB’s inv function or MATLAB’s
Gauss-Elimination function, we will skip the method of determinants.
a2 ,1x1 + a2 , 2 x2 + a2 , 3 x3 + + a2 , n xn = c2
(7.1)
an ,1x1 + an , 2 x2 + an , 3 x3 + + an , n xn = cn
where the a’s and the c’s are known and the x’s are the unknowns.
In matrix algebra we can write the set of Equations 7.1 as follows:
AX = C
153
154 MATLAB® Essentials
where:
x1 a1,1 a1, 2 a1, n c1
x a a2 , 2
a2 , n c
X= 2
, A=
2 ,1
, C=
2
(7.2)
xn an ,1 an , 2 an , n cn
The unknown vector X has n rows and 1 column. Similarly, the known vector
C has n rows and 1 column. The known coefficient matrix A has n rows and
n columns.
NO T E : In matrix algebra, the number of columns in A must equal the number
of rows in X.
Example 7.1
The following example solves the third-order system of linear equations shown
below, and writes the results to the screen:
3 x1 + 2 x2 − x3 = 10
− x1 + 3 x2 + 2 x3 = 5
x1 − x2 − x3 = −1
% Example_7_1.m
% This program solves a third order linear system of equations by
% MATLAB's inv function and by MATLAB's Gauss elimination method.
clc; clear;
A=[3 2 -1; -1 3 2; 1 -1 -1];
C=[10 5 -1]'; % Transposing a row vector to a column vector.
% check solution:
X1=inv(A)*C % X1 is the solution using MATLAB’s inv function.
X2=A\C % X2 is the solution using MATLAB’s Gauss elimination method.
% Does X2=X1?
% Use the size() command to determine the number of rows and columns.
% Print size of A.
[A_rows A_cols] = size(A);
% Print matrix A.
A
% Print vector C.
C
% Print A*X1, does it give C2=C? \n');
C2=A*X1
end
------------------------------------------------------------------------------
Program Results:
X1 =
-2.0000
5.0000
-6.0000
X2 =
-2.0000
5.0000
-6.0000
A =
3 2 -1
-1 3 2
1 -1 -1
156 MATLAB® Essentials
C =
10
5
-1
C2 =
10.0000
5.0000
-1.0000
>>
--------------------------------------------------------------------------
We see that the use of MATLAB’s Gauss-Elimination method produces the same
answer as the use of MATLAB’s inv function.
Exercises
E7.1. Solve the following set of linear equations by MATLAB’s inv function:
a. 2x1 – x2 = 12
4x1 + 3x2 = –8
b. 2x1 + 3x2 – x3 = 20
4x1 – x2 + 3x3 = −14
x1 + 5x2 + x3 = 21
c. 4x1 + 8x2 + x3 = 8
−2x1 – 3x2 + 2x3 = 14
x1 + 3x2 + 4x3 = 30
Example 7.2
Suppose we have the following system of equations (this system of equations was
determined by the analysis of a truss consisting of 13 structural members sub-
jected to external forces). In the following set of equations, F1 , F2 , F3 ,... F13 represent
the unknown internal forces in the structural members and the right-hand side
of the equations represent external forces, P1 , P2 , P3 ,... P13 applied to the truss mem-
bers at the joints. (For more details on the process see Section 4.4 in Reference 2).
Since there are 13 unknown forces, there will be 13 equations and each equation
will have 13 a’s, most of which will be zero. The equations need to be numbered as
shown below. In the following set of equations, the coefficient matrix A is be made
up of elements ai , j where the first index is the equation number and the second
index is the same number, j, of the index of unknown force, Fj.
0.6 F1 + F2 = 0 (1) We see that only a1,1 and a1, 2 are non-zero.
0.8 F1 = − 62.5 (2) We see that only a2 ,1 is non-zero.
− 0.6 F1 + F5 = 0 (3) We see that only a3 ,1 and a3 , 5 are non-zero.
− 0.8 F1 − F3 = 0 (4) We see that only a4 ,1 and a4 , 3 are non-zero.
− F2 + F6 + 0.6 F4 = 0 (5) We see that only a5 , 2 , a5 , 6 and a5 , 4 are non-zero.
F3 + 0.8 F4 = 50 (6) We see that only a6 , 3 and a6 , 4 are non-zero.
− 0.6 F4 − F5 + F8 + 0.6 F10 = 0 (7) We see that only a7 , 4 , a7 , 5 , a7 , 8 and a7 ,10 are non-zero.
−0.8 F4 − F7 − 0.8 F10 = 0 (8) We see that only a8 , 4 , a8 , 7 and a8 ,10 are non-zero.
− F6 + F9 = 0 (9) We see that only a9 , 6 and a9 , 9 are non-zero.
F7 = 30 (10) We see that only a10 , 7 are non-zero.
− F9 − 0.6 F10 + F11 = 0 (11) We see that only a11, 9 , a11,10 and a11,11 are non-zero.
0.8 F10 + F12 = 40 (12) We see that only a12 ,10 and a12 ,12 are non-zero.
− F12 − 0.8 F13 = 0 (13) We see that only a13 ,12 and a13 ,13 are non-zero.
Since the coefficient matrix is sparse, it is best to initially set all ai , j = 0, and then over-
write the non-zero ai , j terms as specified in the set of equations. In matrix algebra, the
set of equations is of the form AF = P. The program follows:
% Example_7_2.m
% This program solves a system of algebraic, linear equations.
% The system of equations stems from a truss problem in statics.
% The A matrix elements are initially set to zero. The non-zero
% A elements then override the initial values. The first index in the A
% matrix elements represent the equation number. The second index in
% the A matrix element correspond to the index of the force associated with
% that matrix element.
158 MATLAB® Essentials
Program Results:
Example 7.2
Program solves for the internal forces of a truss. Forces in kN.
A matrix
1 2 3 4 5 6 7 8 9 10 11 12 13
-------------------------------------------------------------------
1 0.6 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2 0.8 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
3 -0.6 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
4 -0.8 0.0 -1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
5 0.0 -1.0 0.0 0.6 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
6 0.0 0.0 1.0 0.8 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
7 0.0 0.0 0.0 -0.6 -1.0 0.0 0.0 1.0 0.0 0.6 0.0 0.0 0.0
8 0.0 0.0 0.0 -0.8 0.0 0.0 -1.0 0.0 0.0 -0.8 0.0 0.0 0.0
9 0.0 0.0 0.0 0.0 0.0 -1.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0
10 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0
11 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 -1.0 -0.6 1.0 0.0 0.0
12 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.8 0.0 1.0 0.0
13 0.0 0.0 0.0 0.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 -1.0 0.6
R3
i3
1 R2 R4
v2 3
v1 v3
2
i2 i4
R1 R5
i1 i5
+ +
V1 I1 V2
– –
FIGURE 7.1
A resistive circuit for Example 7.3.
− G3 v1 − G4 v2 + (G3 + G4 + G5 ) v3 = V2 G5 (7.7)
V1 = 12 V , V2 = 3.3 V , I1 = 2 mA
% Example_7_3.m
% Resistive Circuit Problem
% This program solves for the internal node voltages for the circuit
% shown in Figure 7.1.
% The conductances G are in units of Siemens.
% The node voltage V are in units of volts.
System of Algebraic, Linear Equations 161
Program Results:
V1= 12.0 V V2= 3.3 V I1= 2.0e-03 A
g1= 0.00045 S g2= 0.00010 S g3= 0.00014 S
g4= 0.00011 S g5= 0.00030 S
Node # v (volts)
----------------------------
1 12.6
2 20.3
3 9.0
>>
--------------------------------------------------------------------------------
where the tilde (~) variables are a new set of coefficients (to be determined),
and where the new coefficient matrix A is diagonal (i.e., all of the coefficients
left of the main diagonal are zero). Then by back substitution,
xn = cn /an , n
1
xn − 1 = ( cn −1 − an −1, n xn )
an −1, n −1
etc.
a22 x2 + a23 x3 + + a2 n xn = c2
a33 x3 + + a3 n xn = c3
=
0 = cr + 2
0 = cn
System of Algebraic, Linear Equations 163
where r < n and a11 , a22 ,...., arr are not zero. There are two possible cases:
1. No solution exists if any one of the cr+1 through cn is not zero.
2. Infinitely many solutions exits if cr+1 through cn are all zero.
NOTE: If you attempt to solve a system of algebraic, linear equations using
MATLAB’s Gauss-Elimination method, and MATLAB arrives at a set of equa-
tions as shown in Equation 7.9, MATLAB will give you a warning as follows:
“Warning: Matrix is close to singular or badly scaled. Results may be
inaccurate.”
If, in the above set, r = n and a11 , a22 ,...., ann are not zero, then the system
would appear as follows:
a11x1 + a12 x2 + a13 x3 + + a1n xn = c1
a22 x2 + a23 x3 + + a2 n xn = c2
a33 x3 + + a3 n xn = c3 (7.10)
=
ann xn = cn
For this case there is only one solution.
Exercise
E7.2. Use MATLAB’s inv function to solve the following set of linear
equations. Note the warning that MATLAB gives with its solution.
2 x1 + 3 x2 + x3 − x4 = 1
5 x1 − 2 x2 + 5 x3 − 4 x4 = 5
x1 − 2 x2 + 3 x3 − 3 x4 = 3
3 x1 + 8 x2 − x3 + x4 = − 1
--------------------------------------------------------
REVIEW 7.1
Projects
P7.1. The following set of linear equations came from a problem in Statics.
Use the method described in Example 7.2 to solve the following set of linear
equations. The Fi value represents the internal force in structural member
i in kN.
Take Ax = −9 kN, Ay = 7 kN, cos ϑ = 0.6, sin ϑ = 0.8
cos ϑ F1 + F2 = − Ax (1)
sin ϑ F1 = − Ay ( 2)
− cos ϑ F1 + cos ϑ F5 + F6 =0 ( 3)
− F2 + F4 =0 (5)
F3 =2 (6)
− F6 + cos ϑ F9 + F10 =0 (7)
− F7 − sin ϑ F9 =0 (8 )
− F4 − cos ϑ F5 + F8 =0 (9)
sin ϑ F5 + F7 =4 (10)
F11 =0 (12)
P7.2. The following set of linear equations came from a problem in Statics.
Use the method described in Example 7.2 to solve the following set of linear
equations. The Fi value represents the internal force in structural member
i in kN.
0.8 F2 = 30 (1)
F3 + 0.8 F5 =0 (3)
− F1 + F4 + 0.6 F5 =0 (4)
−0.8 F2 − F3 =5 (5)
−0.6 F2 + F6 =0 (6)
−0.8 F5 − F7 =5 (9)
−0.6 F5 − F6 + F8 =0 (10)
− F8 − 0.6 F9 =0 (12)
FIGURE P7.1
Fourth-order ladder network.
Create a MATLAB program to solve for all circuit voltages. Take V1 = 5V and
the following resistor values:
n= j −1
jth payment = M = x j + P −
∑
n=1
xn I
(P7.4a)
where:
M is the monthly payment
P is the amount borrowed
I is the monthly interest rate = annual interest rate/12
System of Algebraic, Linear Equations 167
References
1. Kreyszig, E., Advanced Engineering Mathematics, 8th ed., Wiley, New York, 1999.
2. Bober, W., Introduction to Numerical and Analytical Methods with MATLAB for
Engineers and Scientists, CRC Press, Boca Raton, FL, 2014.
8
Curve Fitting
8.1 Introduction
There are many occasions in engineering that require an experiment to
determine the behavior of a particular phenomenon. The experiment may
produce a set of data points that represents a relationship between the
variables involved in the phenomenon. We may then wish to express this
relationship analytically for further analysis. A mathematical expression
that describes the data is called an approximating function. There are two
approaches to determining an approximating function:
169
170 MATLAB® Essentials
MATLAB measures the precision of the fit with a function named mse, which
is defined as follows:
1 n
mse = ∑ ( y i − y c , i )2 (8.3)
n i =1
where yi are the data point y values and yc,i are the approximating curve y
values at the data points xi , and n is the number of data points.
You may also use polyval(a, x), where x is any set of x values, preferably
between x1 and xn.
Example 8.1
% Example_8_1.m
% This program determines the best fit polynomial approximating
% functions of orders 2 thru 5 for the data set listed below.
% MATLAB’s polyfit and polyval functions are used in the program.
% The sprintf command is used in this program to write formatted data
% in the plot title. The sprintf command is the same as the
% fprintf command except that it returns the data in a MATLAB
% string rather than writing to the screen or to a file.
clear; clc;
% Enter data.
x=-10:2:10;
y=[-980 -620 -70 80 100 90 0 -80 -90 10 220];
mse=zeros(4);
% Determine best fit 2-5 degree polynomials to fit the data.
for m=2:5
fprintf('m= %i \n',m);
coef=zeros(m+1);
coef=polyfit(x,y,m);
% Approximating function at x
yc=polyval(coef,x);
% yc is a vector since x is a vector.
mse(m)=sum((y-yc).^2)/length(x);
% y-yc=[y(1)-yc(1) y(2)-yc(2) ..... y(n)-yc(n)].
fprintf(' x y yc \n');
fprintf('------------------------------\n');
for i=1:length(x)
fprintf('%5.1f %5.1f %8.2f \n',x(i),y(i),yc(i));
Curve Fitting 171
end
fprintf('\n\n');
x2=-10:0.5:10;
% Approximating function at x2
yc2=polyval(coef,x2);
subplot(2,2,m-1),plot(x2,yc2,x,y,'o'), xlabel('x'), ylabel('y'),
grid, axis([ -10 10 -1500 500]),
legend('approx curve','data points');
title(sprintf('Degree %d polynomial fit',m));
end
fprintf(' m mse \n')
fprintf('------------------\n');
for m=2:5
fprintf('%d %8.1f \n',m,mse(m))
end
-------------------------------------------------------------------------------
Program Results:
Output for m = 5 is only displayed here.
m = 5
x y yc
------------------------------
-10.0 -980.0 -999.09
-8.0 -620.0 -545.31
-6.0 -70.0 -156.76
-4.0 80.0 78.39
-2.0 100.0 148.18
0.0 90.0 93.80
2.0 0.0 -13.50
4.0 -80.0 -95.45
6.0 -90.0 -89.91
8.0 10.0 26.15
10.0 220.0 213.50
m mse
------------------
2 32842.4
3 2660.0
4 2342.1
5 1502.9
>>
As expected, the mse decreases as the order of the fitted polynomial is increased.
See Figure 8.1.
--------------------------------------------------------------------------
172 MATLAB® Essentials
0 0
−500 −500
y
y
−1000 approx curve −1000 approx curve
data points data points
−1500 −1500
−10 −5 0 5 10 −10 −5 0 5 10
x x
Degree 4 polynomial fit Degree 5 polynomial fit
500 500
0 0
−500 −500
y
FIGURE 8.1
Approximating curves with data points.
Example 8.2
This example involves the sampling with respect to time of an audio signal that is
converted to a voltage by a microphone and an amplifier. The data are in volts (V)
versus time in microseconds (µs).
% Example_8_2.m
% This program determines the best fit polynomial approximating
% functions of orders 2 thru 5 for the data set listed below.
% MATLAB's polyfit and polyval functions are used in the program.
% The data involves the sampling in time, t, of an audio signal
% converted to a voltage, V, by a microphone and an amplifier.
% V is in volts and t is in microseconds.
clear; clc;
% Define original data points for V(t)
t = [ 0 4 8 12 16 20 24 28 32 36 40 44 48 52 56 ];
V = [.7 .9 .9 .7 .3 0 -.3 -.7 -.7 -.3 0 .3 .7 .7 .3 ];
% Determine best fit 2-5 degree polynomials to fit the data.
for m=2:5
fprintf('m= %i \n',m);
coef=zeros(m+1);
coef=polyfit(t,V,m);
% Approximating function at t
Vc=polyval(coef,t);
mse(m)=sum((V-Vc).^2)/length(t);
Curve Fitting 173
fprintf(' t V Vc \n');
fprintf('(micro-sec) (volt) (volt) \n');
fprintf('------------------------------------------\n');
for i=1:length(t)
fprintf(' %5.1f %8.4f %8.4f \n',...
t(i),V(i),Vc(i));
end
fprintf('\n\n');
t2 = 0:60;
% Approximating function at t2
Vc2=polyval(coef,t2);
subplot(2,2,m-1),plot(t2,Vc2,t,V,'o'), xlabel('t(\mus)'),
ylabel('V(V)'), grid, legend('approx curve','data points'),
title(sprintf('Degree %d polynomial fit',m));
end
fprintf('m mse \n')
fprintf('---------------------\n');
for m=2:5
fprintf('%d %8.5f \n',m,mse(m))
end
---------------------------------------------------------------------------------
Program Results:
Only results for m = 5 are displayed.
m = 5
t V Vc
(micro-sec) (volt) (volt)
------------------------------------------
0.0 0.7000 0.6791
4.0 0.9000 0.9377
8.0 0.9000 0.9102
12.0 0.7000 0.6748
16.0 0.3000 0.3211
20.0 0.0000 -0.0588
24.0 -0.3000 -0.3790
28.0 -0.7000 -0.5691
32.0 -0.7000 -0.5833
36.0 -0.3000 -0.4088
40.0 0.0000 -0.0754
44.0 0.3000 0.3361
48.0 0.7000 0.6845
52.0 0.7000 0.7592
56.0 0.3000 0.2717
m mse
---------------------
2 0.10789
3 0.10583
4 0.00803
5 0.00446
>>
V(V)
V(V)
0 0
−1 −1
0 20 40 60 0 20 40 60
t(µs) t(µs)
Degree 4 polynomial fit Degree 5 polynomial fit
2 1
approx curve
data points
1 0
V(V)
V(V)
0 −1
approx curve
data points
−1 −2
0 20 40 60 0 20 40 60
t(µs) t(µs)
FIGURE 8.2
Approximating function and data points for audio signal versus time.
zc = a1 x + a2 (8.5)
For the data points ( x1 , y1 ), ( x2 , y2 ), , ( xn , yn ), the new set of data points
becomes ( x1 , z1 ), ( x2 , z2 ), , ( xn , zn ).
Curve Fitting 175
Example 8.3
Suppose we took an oscilloscope picture of the position, y, of the mass in a mass-
spring-dashpot system as shown in Figure 8.3 and measured the (t, ye) positions of
the envelope. Table 8.1 gives the measured position, ye , as a function of time, t. The
governing equation of the envelope is
c
− t
y e = y0 e 2m
(8.6)
where:
c is the damping constant
m is the mass
ye is the ordinate position of the envelope of the plot of the mass displacement from
the equilibrium position
y vs. t
2
(t2, y2)
1.5 (t3, y3)
(t4, y4)
1
0.5
y(m)
−0.5
−1
−1.5
−2
0 2 4 6 8 10 12 14 16 18 20
t(s)
FIGURE 8.3
Position of a mass in a mass-spring-dashpot system with its envelope.
176 MATLAB® Essentials
TABLE 8.1
ye versus t
t (s) ye (cm)
0.00 2.00
2.17 1.58
4.31 1.32
6.72 1.04
8.96 0.89
11.21 0.68
13.28 0.55
15.52 0.41
17.93 0.36
c
β2 = y0 and β1 = with t replacing x
2m
c = 2 m β1
Program Results:
a(1)= -0.097, a(2)= 0.695
beta(1)= 0.097, beta(2)= 2.005
m= 25.0(kg), The damping constant= 4.8718(N-s/cm)
>>
log(ye) vs. t
2
1.8
1.6
1.4
1.2
1
log(ye)
0.8
0.6
0.4
0 2 4 6 8 10 12 14 16 18
t(s)
FIGURE 8.4
Plot of log(ye) versus t.
178 MATLAB® Essentials
yc vs. t
2.2
yc
2 ye
1.8
1.6
1.4
yc(cm)
1.2
0.8
0.6
0.4
0.2
0 2 4 6 8 10 12 14 16 18
t(s)
FIGURE 8.5
Plot of yc and ye versus t.
REVIEW 8.1
Given a set of (n + 1) data points (xi , yi), i = 1, 2,…, (n + 1), the method of
cubic splines develops a set of n cubic functions, such that y(x) is represented
by a different cubic in each of the n intervals and the set of cubics passes
through all (n + 1) data points.
yy = spline(xi , yi , xx)
where (xi , yi) is a given set of data points and yy is the value of y at xx.
The spline function determines the four cubic coefficients for each sec-
tion in the given data and will evaluate yy by the cubic-spline method. The
same result can be obtained by using MATLAB’s interp1 function and
specifying the use of the spline method of interpolation. The syntax for
interpolating by the spline method is
yi = interp1( x , y , xi , 'spline')
Example 8.4
The following example involves a measured increase in air pressure at distances
from a blast. The data specifies the pressure above normal atmospheric pressure and
is designated as overpressure. The program demonstrates the use of the MATLAB’s
spline function as well as MATLAB’s interp1 function with the spline option
to determine the pressure at distances not in the data. We see that the two meth-
ods produce the same results. The program follows:
% Example_8_4.m
% This program uses both MATLAB's spline function and MATLAB's
% interp1 function with the cubic spline option to determine the
% over-pressure resulting from a blast. The program calculates the
% over-pressure at locations between data points. The over-pressure
% is in kPa and the distance from the blast in km.
clear; clc;
dist=0.52:0.3:4.12;
press=[165.5 96.5 69.0 52.4 37.2 27.6 21.4 17.2 13.8 11.7 ...
10.3 9.0 7.2];
d=0.52:0.1:4.12;
p1=spline(dist,press,d);
p2=interp1(dist,press,d,'spline');
fo=fopen('output.txt','w');
fprintf(fo,'Peak over-pressure vs. distance from the blast, \n');
fprintf(fo,'Cubic spline fit \n');
fprintf(fo,'dist(km) over-press(kPa) over-press(kPa) \n');
fprintf(fo,' by spline function by interp1 \n');
fprintf(fo,'------------------------------------------------\n');
180 MATLAB® Essentials
for n=1:length(d)
fprintf(fo,'%5.2f %10.2f %10.2f \n',d(n),p1(n),p2(n));
end
plot(d,p1,d,p2,'o'), xlabel('km from ground zero'),
ylabel('overpressure(kPa)'), grid,
title('Peak over-pressure vs. distance from blast')
fclose(fo);
----------------------------------------------------------------------
Program Results:
Peak over-pressure vs. distance from blast, cubic spline fit
dist(km) over-press(kPa) over-press(kPa)
by spline function by interp1
------------------------------------------------
0.52 165.50 165.50
0.62 135.72 135.72
0.72 113.15 113.15
0.82 96.50 96.50
0.92 84.46 84.46
1.02 75.72 75.72
1.12 69.00 69.00
1.22 63.15 63.15
1.32 57.71 57.71
1.42 52.40 52.40
1.52 47.02 47.02
. . .
. . .
3.12 12.28 12.28
3.22 11.70 11.70
3.32 11.19 11.19
3.42 10.73 10.73
3.52 10.30 10.30
3.62 9.88 9.88
3.72 9.46 9.46
3.82 9.00 9.00
3.92 8.49 8.49
4.02 7.89 7.89
4.12 7.20 7.20
Example 8.5
Example 8.2 can also be used as an example for the use of MATLAB’s interp1 func-
tion with the spline option. That example involved the sampling with respect to time
of an audio signal that is converted to a voltage by a microphone and an amplifier.
The data is in volts (V) versus time in microseconds (µs). Variable names in this pro-
gram differ from those in Example 8.2. The program follows:
Curve Fitting 181
140
120
overpressure(kPa)
100
80
60
40
20
0
0.5 1 1.5 2 2.5 3 3.5 4 4.5
km from ground zero
FIGURE 8.6
Blast overpressure versus distance from blast.
% Example_8_5.m
% This program uses interpolation by cubic splines to upsample
% an audio signal V(t) vs. time in microsec.
clear; clc;
% Define original data points for V(t) (time is in microsec)
orig_t = [ 0 4 8 12 16 20 24 28 32 36 40 44 48 52 56 ];
orig_V = [.7 .9 .9 .7 .3 0 -.3 -.7 -.7 -.3 0 .3 .7 .7 .3 ];
% Define upsampled time points
upsample_t = 0:60;
% Calculate interpolated data points using cubic splines
upsample_V = interp1(orig_t,orig_V,upsample_t,'spline');
% Print output to screen
fprintf('Upsampling via cubic spline fit \n');
fprintf('time (microsec) upsample_V \n');
for i=1:length(upsample_t)
fprintf('%8.2f %10.3f \n',upsample_t(i),upsample_V(i));
end
plot(orig_t,orig_V,'o',upsample_t,upsample_V);
xlabel('t(microsec)'); ylabel('V(volt)'); grid;
title('Upsampling with Cubic Spline Interpolation');
legend('original','upsampled');
----------------------------------------------------------------------
Program Results:
Only the plot (Figure 8.7) is shown here.
182 MATLAB® Essentials
0.6
0.4
0.2
V(volt)
−0.2
−0.4
−0.6
−0.8
0 10 20 30 40 50 60
t(microsec)
FIGURE 8.7
Upsampling of audio signal.
Projects
P8.1. A formula describing the fluid level, h, in a tank as a function of time as
the fluid discharges through a small circular orifice (see Figure P8.1) is
2
Cd Ao C A
h = ho − 2 g ho × t + d o × 2 g t2 (P8.1)
AT 2 AT
where:
Cd is the discharge coefficient
ho is the fluid level in the tank at time, t = 0
Ao is the area of the orifice
AT is the cross-sectional area of the tank
Water level
h(t)
Ruler
FIGURE P8.1
Water in a tank discharging through an orifice.
hexp = [0.288 0.258 0.234 0.215 0.196 0.178 0.160 0.142 0.125 0.110 …
0.095 0.080 0.065 0.053 0.041 0.031 0.022 0.013 0.006 0.0022 …
0.000]
Diameter of the orifice, do = 0.0055 m and the diameter of the tank,
DT = 0.146 m. The free surface elevation, ho , at t = 0 is 0.288 m. The gravita-
tional constant, g = 9.81 m/s2.
Use the mse as defined by Equation P8.2 to determine the value for Cd that
best fits the data. Vary Cd from 0.3 to 0.9 in steps of 0.01 and evaluate the mse
for each Cd selected, where
N
∑[ h(t ) − h
1
mse = i exp (ti )]2 (P8.2)
N i =1
where:
N is the number of data points
h(ti) is the water level in the tank at ti as determined by Equation P8.1
hexp(ti) is the water level in the tank at ti as determined by experiment
For the Cd with the lowest mse, create a plot of h versus t (solid line) and
superimpose hexp versus t as little x’s onto the plot of h versus t. Also print out
the value of Cd that gives the lowest mse.
TABLE P8.1
Experimental H versus Q Data
Q H Q H
(m3/h) (m) (m3/h) (m)
P8.3. Figure P8.2 shows a resistor-diode circuit using a type 1N914 silicon
diode (D1) and a 10 kΩ resistor (R1). Table P8.2 shows a list of laboratory
measurements of v2 for various applied voltage levels of v1 at room tempera-
ture (300 K). An equation that describes the behavior of the diode is given in
Equation P8.3.
1. Use the technique described in Section 8.3 to find the best-fit values
for IS and vT .
R1
+
v1
+
−
D1 v2
−
FIGURE P8.2
Diode-resistor circuit for laboratory measurement of diode I-v curve.
Curve Fitting 185
TABLE P8.2
Laboratory Measurements of
Resistor-Diode Circuit
v1 (volts) v2 (volts)
0.333 0.317
0.393 0.356
0.819 0.464
1.067 0.487
1.289 0.501
1.656 0.518
1.808 0.522
2.442 0.541
3.949 0.566
4.971 0.579
6.005 0.588
6.933 0.595
7.934 0.602
9.014 0.607
10.040 0.613
11.009 0.619
15.045 0.634
19.865 0.647
24.64 0.657
29.79 0.666
v2 − v1 v
= IS exp 2 (P8.3)
R1 vT
Plot both the lab data and your fitted curve on the same axes.
v1 − v2
NO T E : The diode current, iD = .
R1
2. vT = kT q is known as the thermal voltage (where k is the Boltzmann
constant and q is the unit electric charge). For your best-fit value for
vT , what is the corresponding temperature value T (in Kelvin)? Take
k = 1.38e–23, q = 1.6e–19.
9
Numerical Integration
9.1 Introduction
In this chapter, we cover Simpson’s rule for approximating the value of defi-
nite integrals as well as MATLAB®’s integral function. Understanding the
concept in Simpson’s rule will help you implement MATLAB’s integral
function for evaluating definite integrals. A discussion of MATLAB’s
integral2 function is also included. Finally, examples demonstrating the
usage of these three methods are given.
x N +1
∆x
I=
∫
x1
f ( x)dx =
3
[ f1 + 4 f2 + 2 f3 + 4 f4 + 2 f5 + + 4 fN + fN +1 ] (9.1)
187
188 MATLAB® Essentials
A2 strips
f (x)
f1 . . . fi − 1 fi fi + 1
...
fN + 1
... Δx Δx
...
x
x1 . . . xi − 1 xi xi + 1 . . . xN + 1
FIGURE 9.1
Area under two adjacent strips.
f2 f3
f1
f
fn − 1
fn
A1 A2 A3 fn + 1
An/2
x
x1 x2 x3 xn + 1
FIGURE 9.2
Summing all two-strip areas in Simpson’s rule.
Example 9.1
Solve by Simpson’s rule:
10
∫
I = ( x 3 + 3.2 x 2 − 3.4 x + 20.2)dx
0
(9.2)
% Example_9_1.m
% This program calculates an integral given in Equation 9.2 by
% Simpson's Rule.
% The integrand is: x^3+3.2*x^2-3.4*x+20.2
% The limits of integration are from 0-10.
clear; clc;
A=0; B=10;
N=100; dx=(B-A)/N;
% Compute values of x and f at each point:
% An arithmetic expression involving vector x produces a vector f.
% Need to use element by element multiplication.
x = A:dx:B;
Numerical Integration 189
f = x.^3+3.2*x.^2-3.4*x+20.2;
% Use two separate loops to sum up the even and odd terms
% of Simpson's Rule. Also, exclude endpoints in the loop, that is
% f(1) and f(N+1).
sum_even=0.0;
for i=2:2:N
sum_even=sum_even+f(i);
end
sum_odd=0.0;
for i=3:2:N-1
sum_odd=sum_odd+f(i);
end
% Calculate integral as per Equation 9.2.
I = dx/3 * (f(1) + 4*sum_even + 2*sum_odd + f(N+1));
% Display results
fprintf('Integrand: x^3+3.2*x^2-3.4*x+20.2 \n');
fprintf('Integration limits: %.1f to %.1f \n',A,B);
fprintf('Simpson rule solution, I = %9.4f \n',I);
% Compare with analytic solution.
% Analytic solution:
I2 = 0.25*10^4+3.2/3*10^3-3.4/2*10^2+20.2*10;
fprintf('Analytic solution, I2 = %9.4f \n',I2);
-----------------------------------------------------------------------------
Program Results:
Integrand: x^3+3.2*x^2-3.4*x+20.2
Integration limits: 0.0 to 10.0
Simpson rule solution, I = 3598.6667
Analytical solution, I2 = 3598.6667
>>
-------------------------------------------------------------------------------
We see that solving the integral of Example 6.1 by Simpson’s rule gives the
same answer as the analytical method up to four decimal places.
Exercises
3
dx
1. I =
∫ 5e
0
3x
+ 2 e −3 x
π/2
sin x dx
2. I =
∫
− π/2
1 − 4 sin 2 x
π
∫
3. I = (sinh x − cos x) dx
0
190 MATLAB® Essentials
The above integral is improper since both the numerator and denominator
are zero at the lower limit (x = 0). The exact value of I can be obtained by resi-
due theory in complex variables and in this case the integral, I, evaluates to
(π2/12) = 0.822467. MATLAB’s integral function, which is discussed next,
is able to evaluate some improper integrals, but may give you a warning that
the answer may be inaccurate.
Q = integral(FUN,A,B)
where FUN is a function handle for the self-written function that describes
the integrand. A and B are the limits of integration and Q is the integral
result. The integral function approximates the integral using global adap-
tive quadrature and default error tolerances. Although the integral func-
tion can treat integrand variables that are complex, we are only interested for
cases where the integrand involves only scalar value functions. The function
will accept limits of integration A or B as inf or –inf. The function Y=FUN(X)
should accept a vector argument X and return a vector result Y. The inte-
grand is evaluated at each element of X. The function FUN can be either as a
separate .m file or as an anonymous function. You may use the latter method
if the integrand can be expressed in a single line.
The integral function is also able to evaluate certain improper integrals.
It does this by selecting limits of integration that are very close to the singular
points, but not on them, thus, removing the singularity.
Numerical Integration 191
Example 9.2
We will now repeat Example 9.1, but this time we will use MATLAB’s integral
function to do the integration. The integral I in Example 9.1 is
10
∫
I = ( x 3 + 3.2 x 2 − 3.4 x + 20.2)dx
0
% Example_9_2.m
% This program evaluates the integral of the function 'f1'
% between A and B by MATLAB's integral function. Since the function 'f1'
% is just a single line, we can use the anonymous form of the function.
clear; clc;
f1=@(x) (x.^3+3.2*x.^2-3.4*x+20.2);
A=0.0; B=10.0;
I = integral(f1,A,B);
% Note f1 is not enclosed by single quotation marks.
fprintf('Integration of f1 over [%.0f,%.0f] ',A,B);
fprintf('by MATLAB''s integral function:\n');
fprintf('f1 = x^3+3.2*x^2-3.4*x+20.2 \n');
fprintf('integral = %10.4f \n',I);
--------------------------------------------------------------------------
Program Results:
Integration of f1 over [0,10] by MATLAB's integral function:
f1 = x^3+3.2*x^2-3.4*x+20.2
integral = 3598.6667
>>
--------------------------------------------------------------------------
We see that the results are the same as those obtained in Example 9.1.
Example 9.3
1
t
EVALUATE: I 2 =
∫t
0
3
+t+1
dt
% Example_9_3.m
% This program evaluates the integral of Example 9.3 by MATLAB's
% integral function. A separate .m file describes the integrand
% to be integrated.
% The integrand is t/(t^3+t+1.0)
clear; clc;
A=0.0; B=1.0;
I2 = integral(@f2_func,A,B);
fprintf('Integration of integrand over [%.0f,%.0f] ',A,B);
fprintf('by MATLAB''s integral function:\n');
fprintf('Integrand = t/(t^3+t+1) \n');
fprintf('integral=%f \n',I2);
192 MATLAB® Essentials
-------------------------------------------------------------------------
% This function works with Example_9_3.m
function f=f2_func(t)
f = t./(t.^3+t+1.0);
-------------------------------------------------------------------------
Program Results:
Integration of integrand over [0,1] by MATLAB’s integral function:
Integrand = t/(t^3+t+1)
integral=0.260069
>>
--------------------------------------------------------------------------
Example 9.4
% Example_9_4.m
% This program evaluates the improper integral log(1+x)/x with
% limits from 0 to 1 using MATLAB's integral function.
clear; clc;
I3=@(x) log(1+x)./x;
A=0; B=1;
fprintf('This program uses MATLAB's integral function to \n');
fprintf('evaluate the improper integral of log(1+x)/x \n');
fprintf('from %2.0f to %2.0f. \n',A,B);
I = integral(I3,A,B);
fprintf('I = %10.6f \n',I);
--------------------------------------------------------------------------------
Program Results:
This program uses MATLAB's integral function to evaluate
the improper integral of log(1+x)/x from 0 to 1.
I = 0.822467
>>
------------------------------------------------------------------------------------
Exercises
∫
3. I = (sinh x − cos x) dx
0
1
3 e x dx
4. I =
∫
0
1− x2
1
log(1 + x )dx
5. I =
∫
0
( 1− x )
1
log(1 + x) dx
6. I =
∫
0
( 1− x2 )
REVIEW 9.1
1. What is the formula for evaluating the integral, I = ∫ AB f ( x) dx by
the Simpson’s rule?
2. What is the name of MATLAB’s function for integrating a
single variable function?
3. In MATLAB’s function for integrating a single variable function
how does one define the function to be integrated?
4. If the integrand contains nonlinear terms, how must they be
treated?
5. Will MATLAB’s integral function treat improper integrals?
194 MATLAB® Essentials
Example 9.5
Calculate the volume of a hemisphere of radius, R, by MATLAB’s integral2
function.
To find the volume, we define a differential volume element, dV, as follows:
dV = R 2 − x 2 − y 2 dxdy (as shown in Figure 9.3) and double-integrate over the inter-
vals x = [−R, R] and y = [−sqrt(R 2 − x 2 ), sqrt(R 2 − x 2 )].
% Example_9_5.m
% This program calculates the volume of a hemisphere (with R=1)
% using MATLAB's integral2 function. The solution is compared with the
% known exact solution for the volume of a hemisphere.
clear; clc;
R = 1;
ymin=@(x) -sqrt(R^2-x.^2);
ymax=@(x) sqrt(R^2-x.^2);
funz=@(x,y) sqrt(R^2-x.^2-y.^2);
V = integral2(funz,-R,R,ymin,ymax);
V_exact = 2/3*pi*R^3;
% print results
fprintf('Volume V of a hemisphere of radius %.1f m \n',R);
fprintf('V by intgral2 = %.4f m^3\n',V);
fprintf('V exact = %.4f m^3\n',V_exact);
---------------------------------------------------------------------------
Numerical Integration 195
R2 − x2 − y2
y
R
dx
dy
FIGURE 9.3
Infinitesimal volume inside a hemisphere.
Program Results
Volume V of a hemisphere of radius 1.0 m
V by intgral2 = 2.0944 m^3
V exact = 2.0944 m^3
>>
---------------------------------------------------------------------------
Example 9.6
The object shown in Figure 9.4 is enclosed by two curves, one of which is a straight
line and the other is a parabola. The object thickness, ∆z , is 5 cm. Take the object mate-
rial to be steel with a mass density, ρ = 8000 kg/m3. The dimensions in the figure are
also in cm.
NO T E : m = ρ ∆ z
∫∫ dx dy
A
integration region
4
3.5
2.5
yc1 & yc2
1.5
0.5
0
−1 −0.5 0 0.5 1 1.5 2
x
FIGURE 9.4
Object enclosed by two curves.
% Example_9_6.m
% This example determines the mass of an object that is enclosed
% by 2 curves. The lower curve is a parabola, y=x^2, and the upper
% curve is a straight line,y=x+2
% x range is from -1 to 2.
% y range is from 0 to 4.
% m=dz*Integration of (rho dx dy) from ymin to ymax.
% The input variables to FUN of MATLAB's integral2 function is (x,y).
% Since the integrand is 1, we needed to express the integrand as x./x
clear; clc;
rho=8e-3;
fun_9_6= @(x,y) x./x;
ymin=@(x) x.^2;
ymax=@(x) x+2;
dz=5.0;
m=dz*rho*integral2(fun_9_6,-1,2,ymin,ymax);
fprintf('m = %8.4f (kg) \n',m)
fprintf('\n');
x=-1:3/60:2;
ymin=x.^2;
ymax=x+2;
fprintf(' j x(cm) ymin(cm) ymax(cm) \n');
fprintf('-------------------------------------------\n');
for j=1:2:length(x)
fprintf('%2i %8.2f %8.4f %8.4f \n',...
j,x(j),ymin(j),ymax(j));
end
Numerical Integration 197
Program Results:
m = 0.1800 (kg)
REVIEW 9.2
Projects
P9.1. This exercise is from Thermodynamics. The entropy change of an ideal
gas from state (T1 , p1) to state (T2 , p2) is given by
T2
dT p2
s(T2 , p2 ) − s(T1 , p1 ) =
∫ c (T ) T
T1
p − R ln
p1
(P9.1)
where:
s is the entropy (kJ/kg-K)
cp is the specific heat at constant pressure (kJ/kg-K)
198 MATLAB® Essentials
M = 44.01 kg/kmol
z Point charge Q
located at rp
+
Measurement
rp r
location ro
ro
E
y
x
(a)
z
Differential line
…+++++++++++++++++…
r Measurement
Line charge of density location
λ coul/m along ±z axis rp
ro dE
(b)
FIGURE P9.1
(a) Electric field at (xo , yo , zo) due to point charge at (xp , yp , zp). (b) Electric field at (xo , yo , zo) due
to line charge element λdz located along the z-axis.
200 MATLAB® Essentials
where
2 L
nπx
an =
L ∫ 0
f ( x )sin
L
dx (P9.6)
and
f ( x ) = Y ( x , 0) (P9.7)
0.4 x , 0 ≤ x ≤ 0.75 L
f (x ) = (P9.8)
1.2 − 1.2 x , 0.75 L ≤ x ≤ L
P9.5. The components of the electric field Ex , Ey , and Ez resulting from a line
of point charges with a linear charge density, λ, with units Coulomb/meter,
which is evenly distributed along the z-axis from z = −0.01 m to z = +0.01 m
(see Figure P9.1) is given by
0.01
λdzp xo − xp
Ex ( xo , yo , zo ) =
∫
−0..01 (
4πε o ( x − x )2 + ( y − y )2 + ( z − z )2
o p o p o p )
3
2
(P9.9)
0.01
λdzp yo − yp
Ey ( x o , y o , z o ) =
∫
−0..01 (
4πε o ( x − x )2 + ( y − y )2 + ( z − z )2
o p o p o p )
3
2
(P9.10)
y String
FIGURE P9.2
Vibrating string.
Numerical Integration 201
TABLE P9.1
Table Format for Presenting Ex Values
E x Values
x y
−0.05 −0.03 −0.01 0.01 0.03 0.05
−0.05 — — — — — —
−0.04 — — — — — —
−0.03 — — — — — —
.
.
0.03 — — — — — —
0.04 — — — — — —
0.05 — — — — — —
0.01
λdzp zo − zp
Ez ( xo , yo , zo ) =
∫
−0..01 (
4πε o ( x − x )2 + ( y − y )2 + ( z − z )2
o p o p o p )
3
2
(P9.11)
where:
( xp , yp , zp ) represents the position of the point charges
( xo , yo , zo ) represents a point of interest in the vicinity of the point charges
y = 6 − 1.5 x 2
202 MATLAB® Essentials
dA = (R sinϕ dθ)(Rdϕ)
dϕ
y
R R sinϕ
dθ
FIGURE P9.3
A differential surface area on the hemisphere.
y = −3 x − 6
The object thickness, ∆z, is 5 cm. Take the object material to be steel with a
mass density, ρ = 8000 kg/m3.
NO T E : m = ∆z
∫∫ ρ dxdy.
A
Numerical Integration 203
P9.8. The (xc, yc) position of the center of mass of the object described in
Project P9.7 is given by
mxc = ∆z ρ
∫∫ x dxdy
A
∫∫ y dxdy
myc = ∆z ρ
A
(P9.12)
where:
ρ is the mass density of the material
m is the mass of the object
∆z is the thickness of the object
Create a MATLAB program that will evaluate (xc , yc) using MATLAB’s
integral2 function. Print the results to the screen to four decimal places.
P9.9. Using the infinitesimal volume shown in Figure 9.3 and MATLAB’s
integral2 function, determine the centroid position, zc , of the hemisphere
described in Example 9.5. By symmetry, we can assume that xc = 0 and yc = 0.
Noting that zc for the infinitesimal volume is at the center position, that is,
1
zc dV = R2 − x 2 − y 2 × R2 − x 2 − y 2 dxdy
2
1
∫∫ 2 ( R − x )
2 2
zc V = − y 2 dxdy (P9.13)
A
where:
x = [−R, R] and y = [−sqrt(R2 − x 2 ), sqrt(R2 − x 2 )]
V is the volume of the hemisphere = 2/3πR3
dV = πr 2 dz (P9.14)
where:
r = (R2 − z 2 ) (P9.15)
Thus,
R R
π π z2 z4 3
zc =
V ∫
0
(R2 z − z 3 )dz =
2
× R2 − = R
πR3 2 4 0 8
(P9.16)
3
204 MATLAB® Essentials
dz
r
z
R
FIGURE P9.4
Infinitesimal region used to determine the centroid position zc analytically.
Reference
1. Bober, W., Introduction to Numerical and Analytical Methods with MATLAB for
Engineers and Scientists, CRC Press, Boca Raton, FL, 2014.
10
Numerical Integration of Ordinary
Differential Equations
10.1 Introduction
Many ordinary differential equations (ODE) result from a particular physi-
cal law. The physical law is a mathematical model of some particular physi-
cal phenomenon. Many of the equations that have been used in this book
are based on Newton’s second law of motion. For example, the equations
used to describe the motion of a free falling ball in a gravitational field
(Example 2.7) or the motion of the mass in a mass-spring-dashpot system
(Exercise E2.3-for a complete derivation of the governing equations, see
Project P2.5 in Reference 1), or the velocity and position of the basketball
(Exercise E2.4) are differential equations based on Newton’s second law.
The voltage in a parallel RLC circuit (Exercise E2.6) resulted from several
electrical laws, including Kirchhoff’s current law, which resulted in an ordi-
nary differential equation whose solution is given in Equation 2.13 (for a
complete derivation of the governing equations, see P2.7 in Reference 1).
Ordinary differential equations can be broken up into two categories:
1. Initial value problems are those in which the initial conditions of the
variables are known. All of the examples and exercises mentioned
above fall into this category. Additional examples include launch-
ing a rocket with a known initial position and velocity or the value
of a circuit node voltage (or its slope) at t = 0. In this chapter, we
only cover the initial value problem along with MATLAB ®’s built-in
ode45 function to solve these types of problems.
2. Boundary value problems in which we know variable conditions at
specific coordinates in the problem geometry. For example, deter-
mining the temperature at various positions along a bar when the
end temperatures at the bar ends are known. Other examples include
determining the deflection of a beam along its length when the deflec-
tion at its ends is known, or determining the electric potential along
the length of a conductor when the electric potential at both ends of a
conductor are known. This topic is covered in Chapter 11.
205
206 MATLAB® Essentials
Example 10.1
Let us consider the ball-bearing problem of Example E2.5. Applying Newton’s
second law to the ball bearing gives the following first-order differential equation:
W dV
= 6πRµ( VT − V ) (10.1)
g dt
where:
V is the ball-bearing velocity
V T terminal velocity of the ball bearing = (W − B) 6πR µ
W is the weight of the ball bearing = ρsteel υg
B is the buoyancy acting on the ball bearing = ρfluid υg
R is the radius of the ball bearing
υ is the volume of the sphere = (4 3) πR 3
ρ is the mass density
µ is the viscosity of the fluid
g is the gravitational constant = 9.81 m/s2
To see the full derivation of Equation 10.1 see Exercise E2.5 in Reference 1.
In the notation of ode45, (dV/dt) = V′
Take µ = 3.85 (N-s)/m2, R = 0.01 m, ρsteel = 7910 kg/m3, ρoil = 899 kg/m3.
We will take V(0) = 0.
% Example_10_1.m
% This program determines the velocity of a ball bearing
% dropped in a vat of fluid. The ball bearing reaches a
% terminal velocity when the unbalanced force acting
% on the object is zero.
% The program compares the velocity determined by the
% by both an analytical solution and MATLAB's ode45 function.
clear; clc;
global R mu g VT W VT
R=0.01; rho_steel=7910; rho_fluid=899; mu=3.85; g=9.81;
vol=4/3*R^3;
W=rho_steel*g*vol;
B=rho_fluid*g*vol;
VT=(W-B)/(6*pi*R*mu);
Vo=0;
tspan=0:0.01:0.2;
[t,V]=ode45('dVdt',tspan,Vo);
% Closed form solution is V2
arg=6*pi*R*mu*g/W;
V2=VT*(1-exp(-arg*t));
fprintf('t(s) V(m/s) V2(m/s) \n');
fprintf('---------------------------------\n');
for i=1:length(t)
fprintf('%4.2f %6.4f %6.4f \n',t(i),V(i),V2(i));
end
208 MATLAB® Essentials
Program Results:
See Figure 10.1.
V vs. t
0.14
0.12
0.1
0.08
V(m/s)
0.06
0.04
0.02
0
0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 0.16 0.18 0.2
t(s)
FIGURE 10.1
Velocity of ball bearing versus time.
Numerical Integration of Ordinary Differential Equations 209
Example 10.2
Whenever we deal with a second-order differential equation, we need to reduce the
second-order differential equation to two first-order differential equations. Suppose
we consider the mass motion in a mass-spring-dashpot system of Exercise E2.2. The gov-
erning differential equation is
c k
y′′ + y′ + y= 0 (10.2)
m m
To see the full derivation of Equation 10.2 see Project P2.5 in Reference 1.
To reduce Equation 10.2 to two first-order differential equations, let y′ = V , then
c k
V′ = − V− y
m m (10.3)
y′ = V
% Example_10_2.m
% This program determines the position and velocity
% of a mass in a mass-spring-dashpot system using
% MATLAB's ode45 function.
% m=25 kg; c=5 N-s/m; k=100 N/m;
% Y(1)=y
% Y(2)=V
% Y(1)_prime=Y(2)
% Y(2)_prime= -c/m*Y(2)-k/m*Y(1)
clear; clc;
initial=[0.5 0.0];
tspan=0.0:0.1:10.0;
[t,Y]=ode45(@dYdt,tspan,initial);
y=Y(:,1);
V=Y(:,2);
fprintf(' t(s) y(s) V(m/s) \n');
fprintf('----------------------------------\n');
for i=1:2:101
fprintf('%5.2f %10.4f %10.4f \n',t(i),y(i),V(i))
end
210 MATLAB® Essentials
Program Results:
See Figure 10.2a and b.
y vs. t
0.5
0.4
0.3
0.2
0.1
y(m)
−0.1
−0.2
−0.3
−0.4
−0.5
0 1 2 3 4 5 6 7 8 9 10
(a) t(s)
V vs. t
0.8
0.6
0.4
0.2
0
V(m/s)
−0.2
−0.4
−0.6
−0.8
−1
0 1 2 3 4 5 6 7 8 9 10
(b) t(s)
FIGURE 10.2
(a) Plot of mass displacement versus time and (b) plot of mass velocity versus time.
212 MATLAB® Essentials
Example 10.3
In this example, we consider the voltage in a parallel RLC circuit described in Project
P2.10 (see Figure 2.22). For a complete derivation of the governing equation, see
Project 2.7 in Reference 1. The governing differential equation for the circuit voltage is
d2v 1 dv 1
2
+ + v=0 (10.4)
dt RC dt LC
1 1
u′ = − u− v
RC LC (10.5)
v′ = u
dv 6
=
We will take v(0) 6=
and (0)
dt RC
The program follows:
% Example_10_3.m
% This program determines the voltage in a parallel RLC circuit using
% MATLAB's ode45 function.
% R=100 ohm; L=1 mHc; C=1 microfarad;
% v(0)=6 volt; dvdt=v(0)/(R*C)
% Y(1)=v
% Y(2)=dv/dt=u
% Yprime(1)=Y(2)
% Yprime(2)= -1/(R*C)*Y(2)-1/(L*C)*Y(1)
clear; clc;
global R L C;
R=100; L=1e-3; C=1e-6;
initial=[6 6/(R*C)];
tspan=0:5e-6:5e-4;
[t,Y]=ode45(@dvoltdt,tspan,initial);
v=Y(:,1);
u=Y(:,2);
t2=t*1.0e+6;
fprintf(' t v dv/dt \n');
fprintf('(micro-sec) (volt) (volt/sec) \n');
fprintf('----------------------------------------\n');
for i=1:length(t2)
fprintf(' %5.0f %10.2f %10.0f \n',t2(i),v(i),u(i))
end
plot(t,v), xlabel('t(s)'), ylabel('v(volt)'), grid,
title('v vs. t');
figure;
plot(t,u), xlabel('t(s)'), ylabel('dv/dt(volt/s)'), grid,
title('dv/dt vs. t');
----------------------------------------------------------------------
Numerical Integration of Ordinary Differential Equations 213
Program Results:
See Figure 10.3a and b.
t v dv/dt
(micro-sec) (volt) (volt/sec)
----------------------------------------
0 6.00 60000
5 6.22 27209
10 6.27 -4644
15 6.17 -34837
20 5.93 -62711
25 5.55 -87688
30 5.06 -109310
35 4.46 -127231
40 3.79 -141188
45 3.06 -151018
50 2.29 -156678
. . .
. . .
450 0.36 -20617
455 0.25 -21094
460 0.15 -21033
465 0.04 -20461
470 -0.06 -19418
475 -0.15 -17955
480 -0.24 -16127
485 -0.31 -13996
490 -0.38 -11629
495 -0.43 -9094
500 -0.47 -6462
>>
----------------------------------------------------------------------
214 MATLAB® Essentials
v vs. t
8
4
v(volt)
−2
−4
0 1 2 3 4 5 6
(a) t(s) × 10−4
0.5
0
dv/dt(volt/s)
−0.5
−1
−1.5
−2
0 1 2 3 4 5 6
(b) t(s) × 10−4
FIGURE 10.3
(a) Plot of voltage versus time. (b) Plot of dv/dt versus time.
Numerical Integration of Ordinary Differential Equations 215
Exercises
c k F
y′′ + y′ + y = o sin ωt (10.6)
m m m
1. ω = 1.5 ωn
2. ω = ωn
y1′ = y2 y3t
y′2 = − y1y3
y′3 = −0.51y1y2
dv 1 1
=− v − iL
dt RC C
diL 1
= v
dt L
Projects
P10.1. This project involves determining the temperature of a small solid
aluminum sphere dropped into a fluid contained in a vertical circular cylinder
of radius R. The sphere radius is r and the fluid depth is L. Neglecting heat
transfer to the container walls, the governing equations for this problem are
dT
mc = h As ( Tf − Tal ) (P10.1a)
dt al
dT
mc = h As ( Tal − Tf ) (P10.1b)
dt f
ρal = 2707 kg/m 3 , ρ f = 880 kg/m 3 , cal = 896 J/kg- o C, c f = 1880 J/kg- o C,
o
= =
Tal (0) 80 20o C, r 0=
C, Tf (0) = .2 m , R 0= .5 m, h 890 W/m 2 - o C
.3 m, L 0=
Vairp
y
θ
Ground
FIGURE P10.1
Path of a food package dropped from an airplane.
Numerical Integration of Ordinary Differential Equations 217
Governing equations:
dVx C ρV 2A
=− d cos ϑ (P10.2a)
dt 2M
dVy C ρV 2A
= g− d sin ϑ (P10.2b)
dt 2M
dx
= Vx (P10.2c)
dt
dy
= Vy (P10.2d)
dt
Vx Vy
cos ϑ = , and sin ϑ = (P10.2e)
V V
where:
Cd is the drag coefficient
ρ is the air density
M is the mass of package
A is the frontal area of package
Initial conditions:
=
x ( 0 ) 0=
, y (= =
0 ) 0, Vx ( 0 ) 50 m/s , Vy ( 0 ) 0.
P10.3. Figure P10.2 shows a third-order RLCC circuit. In order to run a time-
domain transient analysis, we transform the circuit into three first-order
differential equations which are
dvC1 1
= (−vC1 + vC 2 + RiL + vS ) (P10.3a)
dt RC1
dvC 2 1
= (vC1 − vC 2 − vS) (P10.3b)
dt RC2
diL 1
= (− vC1 + vS) (P10.3c)
dt L
vC1 vC2
+ − 1 − + 2
iL
iC1 iC2
C1 C2 iR
+
+ +
vS
vL L R vR
− 1 2 −
−
(a)
vS(t)
5V
t (μsec)
0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
(b)
FIGURE P10.2
(a) A third-order RLCC circuit configuration and (b) pulse input.
Numerical Integration of Ordinary Differential Equations 219
We have chosen the three voltages and currents with derivative terms
(vC1, vC2 , and iL) as the state variables for this problem.
Construct a MATLAB program using MATLAB’s ode45 function to solve
for the variables vC1, vC 2 , and iL . Take C1 = 1 μF, C2 = 0.001 μF, R = 100 kΩ,
L = 0.01 mH. Use a time interval of 0 ≤ t ≤ 5 µs and a step size of 0.01 μs.
Assume vS (t) is a 5V pulse starting at time t = 0 with rise time of 0.1 μs, an on
time of 0.8 μs, and fall time of 0.1 μs (as shown in Figure P10.2). Initial condi-
tions: vC1(0) = 0, vC2 (0) = 0 , and iL (0) = 0.
Plot on separate graphs: vC1(t), vC 2 (t), iL (t), and vS (t) versus time.
P10.4. A small rocket with an initial mass of 350 kg, including a mass of
100 kg of fuel, is fired from a rocket launcher (see Figure P10.3). The rocket
leaves the launcher at velocity Vo and at an angle of θo with the horizontal.
Neglect the fuel consumed inside the rocket launcher. The rocket burns fuel
at the rate of 10 kg/s, and develops a thrust T = 6000 N. The thrust acts axi-
ally along the rocket and lasts for 10 s. Assume that the drag force also acts
axially and is proportional to the square of the rocket velocity. The govern-
ing differential equations describing the position and velocity components
of the rocket are as follows:
dx
= Vx (P10.4c)
dt
y
V
θ (t)
y
Ground
3,000 m
x
15 m
x
Vo θo
FIGURE P10.3
Rocket trajectory.
220 MATLAB® Essentials
dy
= Vy (P10.4d)
dt
V 2 = Vx2 + Vy2 (P10.4e)
where:
m is the mass of the rocket (varies with time)
Vx , Vy are the x and y components of the rocket’s velocity relative to the
ground
K is the drag coefficient
g is the gravitational constant
(x, y) are the position of the rocket relative to the ground
t is the time of rocket flight
The target lies on ground, which has a slope of 5%. The ground elevation
relative to the origin of the coordinate system of the rocket is given by
Using a lump parameter analysis (assuming that the engine oil is well mixed)
in heat transfer, the governing equations describing the time temperature
variation of both materials are as follows:
dθ f
= − a1(θ f − θw ) + a5 (P10.5a)
dt
dθw
= a2 (θ f − θw ) − a3θw = a2θ f − ( a2 + a3 )θw (P10.5b)
dt
where:
θ f = Tf − T∞ (P10.5c)
θw = Tw − T∞ (P10.5d)
hi As , i hA hA Q
a1 = , a2 = i s , i , a3 = o s , o , a4 = a2 + a3 , a5 = (P10.5e)
mf c f mw cw mw cw mf c f
Initial conditions:
T∞ = 15°C
dz
=V (P10.6a)
dt
dV 1
= ( B −W − sgn * D ) (P10.6b)
dt M
where:
z is the altitude of the centroid of the balloon
V is the vertical velocity of the balloon
t is the time
B is the buoyancy force acting on the balloon (varies with altitude)
M is the total mass of the balloon material, ballast, and the gas
W is the total weight of the balloon material, ballast, and the gas = Mg
D is the drag on the balloon
sgn = +1, if (dz dt) ≥ 0 and sgn = −1, if (dz dt) < 0
dp p
=− gV (P10.6c)
dt RT
T = Ti − λz (P10.6d)
p
ρ= (P10.6e)
RT
where:
p is the outside air pressure at the centroid of the balloon
ρ is the outside air density at the centroid of the balloon
g is the gravitational constant that varies with altitude
R is the gas constant for air
T is the outside air temperature at the centroid of the balloon
Ti is the temperature at the earth’s surface = 288.15 (K).
λ is the lapse rate
The buoyancy force, B, is given by
B = ρgυ (P10.6f)
and
r
g = g0 e (P10.6g)
z + re
where:
υ is the volume of the balloon = (4/3) rb3
rb is the radius of the balloon
Numerical Integration of Ordinary Differential Equations 223
For low Reynolds Number, Re, less than 0.1, the drag force, D, is given by
Stokes formula, which is
D = 6πµVrb (P10.6h)
ρ 2
D = Cd V A (P10.6i)
2
where:
Cd is the drag coefficient
A is the frontal area of the balloon = πrb2
24 6
Cd = + + 0.4 (P10.6j)
Re 1.0 + Re
where
2ρVrb
Re = (P10.6k)
µ
C1
i3
R1 R2 v2
vin +
v i4 vout
1 i5 −
i1 i2
C2
FIGURE P10.4
Sallen–key circuit.
dvout −1 1
= vout + R C v1 (P10.7a)
dt R C
2 2 2 2
dv1 1 1 1 1 1 1
= − vout + R C − R C − R C v1 + R C vin (P10.7b)
dt R2C1 R2C2 2 2 1 1 2 1 1 1
1. Solve for vout and v1 using MATLAB’s ode45 function. Assume that
the input to the circuit vin is a step voltage that changes from 0 V to
1 V at time t = 0 +. Assume the following values for the circuit ele-
ments: R1 = 5000 Ω, R2 = 5000 Ω, C1 = 2200 pF, C2 = 1100 pF. Use a
time interval of t = [0, 100 µs] s and assume vout=(0) v=
1 (0 ) 0.
2. Find the impulse response of the circuit by first creating a MATLAB
function pulse(t) that returns the following values:
106 for 0 < t < 10 −6
pulse(t) =
0 otherwise
Then, solve for vout and v1 using MATLAB’s ode45 function where
vi = pulse(t). Use the same component values, time interval, and
initial conditions as in part 1.
3. Plot the step response (from part 1) and the impulse response
(from part 2) on the same set of axes. What relationship can you see
between the two?
Numerical Integration of Ordinary Differential Equations 225
where:
ρ is the density of the air
A is the frontal area of the basketball
Cd is the drag coefficient
m is he mass of the basketball
g is the gravitational constant
(Vx , Vy) are the x and y components of the velocity and (x, y) are the hori-
zontal and vertical positions of the basketball
sgn = −1.0 if Vy < 0 and sgn = 1.0 if Vy > 0
Hint: MATLAB’s ode45 function should give you x(i), y(i), Vx(i), Vy(i), for
i = 1:length(t). Determine the first i value when y(i) < 3.048 and Vy(i) < 0. Use
that value of i and the one before it to interpolate the x-position when y = 3.048.
Would the basketball hit the rim of the hoop? The rim radius is 0.2286 m.
226 MATLAB® Essentials
Reference
1. Bober, W., Introduction to Numerical and Analytical Methods with MATLAB for
Engineers and Scientists, CRC Press, Boca Raton, FL, 2014.
11
Boundary Value Problems of
Ordinary Differential Equations
11.1 Introduction
When an ordinary differential equation involves boundary conditions
instead of initial conditions, then a numerical approach is most often used
to solve the problem. In a boundary value problem, we essentially need to fit
a solution into the known boundary conditions as opposed to simply inte-
grating from the initial conditions. An example of this type of problem is
the temperature of a bar subjected to known different temperatures at the
ends as it looses heat along the bar by natural convection. Another example
would be the deflection of a beam due to an applied load along the beam
and where the boundary conditions at both ends of the beam are specified.
Another example of this type of problem is the determination of the electric
field between the plates of a capacitor with a known charge density between
the plates and a fixed voltage across the plates. In these three examples, a
solution is found by numerically solving a second-order, nonhomogeneous
ordinary differential equation using finite difference methods.
227
228 MATLAB® Essentials
TABLE 11.1
Summary of Finite Difference Formulas for Boundary Value Problems
yi +1 − yi First-order forward difference formula. Usually used for a y ’ boundary
y′i =
∆x condition at the beginning of domain.
yi − yi − 1 First-order backward difference formula. Usually used for a y ’ boundary
y′i =
∆x condition at end of the domain.
y i + 1 + y i −1 − 2 y i Second-order central difference formula for the second derivative in the
y′′i = 2 interior of the domain.
∆x
Example 11.1
In this example we consider a bar having a circular cross section that is subjected to
known temperatures at the two ends and which looses heat along the bar by natural
convection to its surroundings (see Figure 11.1). The governing equations describing
the temperature along the bar is given by the following formula:
d 2T hP
= ( T − T∞ ) (11.1)
dx 2 Ak
where:
T is the temperature of the bar at position x
h is the convective heat transfer coefficient
k is the thermal conductivity of the bar material
P is the bar perimeter
A is the bar cross-sectional area
T∞ is the temperature of the surrounding air
Applying the finite difference formulas to the problem gives the following set of
equations:
Ti + 1 + Ti −1 − 2 Ti hP
= ( Ti − T∞ ) (11.2)
∆x 2 kA
h,T∞
h,T∞
FIGURE 11.1
Bar subjected to different end temperatures and losing heat to the surroundings.
Boundary Value Problems of Ordinary Differential Equations 229
We will assume that the x domain is divided into N subdivisions and that T1 = 200°C
and TN+1 = 20°C. Then the set of equations become
T1 = 200 (1)
hP ∆x 2 hP ∆x 2
T1 + T3 − 2 T2 − T2 = T∞ (2)
kA kA
hP ∆x 2 hP ∆x 2
T2 + T4 − 2 T3 − T3 = T∞ (3)
kA kA
hP ∆x 2 hP ∆x 2
T3 + T5 − 2 T4 − T4 = T∞ (4)
kA kA
.
.
hP ∆x 2 hP ∆x 2
TN −1 + TN + 1 − 2 TN − TN = T∞ (N)
kA kA
TN +1 = 20 (N+1)
The above set of algebraic, linear equations can be solved by using MATLAB ®’s inv
function or MATLAB’s Gauss-Elimination function. In Example 7.3, we discussed
a systematic method for solving this type of problem. The set of equations can be
expressed as the matrix equation AT = C, where
hP∆x 2
a2 ,1 = 1, a2 , 3 = 1 and a2 , 2 = − 2 + .
kA
In this expression, A is the cross-sectional area of the bar and not the coefficient
matrix, A. From the pattern of the equation set, we can assign all the ai , j terms
within one for loop. This is done in the following program:
230 MATLAB® Essentials
= =
k 386 W/m-C, h 60 W/m
= 2
-C, L 0=
.5 m , N 50 , D = 0.2 cm
% Example_11_1.m
% This program determines the temperature in a bar having
% different end temperatures and subjected to convective
% heat transfer.
% Units for k are W/m-C, units for h are W/m^2-C
% units for T are C, units for L are m, units for D are cm.
clear; clc;
k=386; h=60; L=0.5; D=0.2e-2;
P=pi*D; A=pi/4*D^2; N=50; dx=L/N;
T(1)=200; T(N+1)=20; Tinf=20;
C1=h/k*P/A^dx^2;
a(1,1)=1; C(1)=200;
a(N+1,N+1)=1; C(N+1)=Tinf;
x=0:dx:L;
for i=2:N
a(i,i-1)=1; a(i,i+1)=1; a(i,i)=-(2+C1); C(i)=C1*Tinf;
end
T=inv(a)*C';
plot(x,T), xlabel('x(m)'), ylabel('T(C)'), grid, title('T vs. x');
fprintf('x(m) T(C) \n')
fprintf('---------------------\n');
for i=1:2:N+1
fprintf('%4.2f %7.2f \n',x(i),T(i));
end
----------------------------------------------------------------------
Program Results:
x(m) T(C)
---------------------
0.00 200.00
0.02 185.00
0.04 171.03
0.06 158.02
0.08 145.91
0.10 134.64
. .
. .
0.40 35.05
0.42 31.55
0.44 28.31
0.46 25.32
0.48 22.55
0.50 20.00
>>
T vs. x
200
180
160
140
120
T(C)
100
80
60
40
20
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5
x(m)
FIGURE 11.2
Plot of temperature, T versus position x.
Exercises
E11.1. Repeat Example 11.1, but this time replace the boundary condition at
x = L, with
dT
−k (L) = h(T (L) − T∞ ) giving
dx
TN +1 − TN
k + hTN +1 = h T∞
∆x
d 2 y M( x )
= (11.4)
dx 2 EI ( x)
where:
y is the deflection of beam
M is the internal bending moment
E is the modulus of elasticity of beam material
I is the moment of inertia of an area
232 MATLAB® Essentials
w (N/m)
y
x
FIGURE 11.3
Deflection of a uniformly loaded beam.
To obtain the finite difference form of the governing equation, subdivide the
x-axis into N subdivisions, giving x1, x2, x3, …, xN+1.
Let the deflections at these points be: y1, y2, y3, …, yN+1.
The finite difference formula for d 2 y/dx 2 , as shown in Table 11.1 is
d2 y y + y − 2 yn
2
( xn ) = n +1 n −21 (11.5)
dt ∆x
yn+1 + yn−1 − 2 yn Mn
=
∆x 2 EI
or
1 1 M ∆x 2
yn − 1 + yn + 1 − yn = n , for n = 2,3,4,..., N (11.6)
2 2 2EI
y1 = 0 (11.7)
y N +1 = 0 (11.8)
wL w xn2
Mn = xn − (11.9)
2 2
Determine the deflection, yi for i = 1:N + 1. Create a plot y versus x and print a
table consisting of yi and xi. Also print out the obtained maximum deflection.
Use the following parameters:
Conducting plates
+
Vo D
x
−
Material between
plates with dielectric ε
and charge density ρ(x)
FIGURE 11.4
Parallel plate capacitor with constant applied voltage.
E11.3. Figure 11.4 shows a parallel plate capacitor with constant applied voltage
vo and a fixed charge density ρ between the plates. For cases with planar sym-
metry such as the parallel plate capacitor where the charge density only changes
in the x-direction (i.e., there is no y or z dependency), then Poisson’s equation
describing the electric potential Φ reduces to an ordinary differential equation:
d 2Φ( x) ρ( x) (11.10)
2
=−
dx ε
where:
Φ( x) is the electric potential (in volts)
ρ( x) is the x-dependent charge density (in coul/m3)
ε is the dielectric constant for the material between the plates
d 2Φ ρ ρ
= − o ( x − D)2 = − o ( x 2 − 2Dx + D2 ) (11.11)
dx 2 ε ε
Equation 11.11 can readily be solved analytically and the solution [2] is
ρo 1 4 D 3 D2 2 εvo D3
Φ( x) = − x − x + x − + x (11.12)
ε 12 3 2 Dρo 4
Solve Equation 11.11 numerically and compare the numerical solution with
the exact solution. Create a plot of Φ versus x and a table consisting of x, Φ
234 MATLAB® Essentials
Projects
P11.1. For the beam shown in Figure P11.1, determine the beam deflection,
y(x), by the finite difference method utilizing MATLAB’s inverse matrix
function or the MATLAB’s Gauss-Elimination Method. Print the results in a
table format. Also determine the approximate maximum deflection. Use the
following parameters:
P = 10 kN , EI = 1.5e + 3 kN-m 2 , L = 10 m , a = 6 m ,
0 ≤ x ≤ 10.0 m in steps of 0.1 m
P ( L − a)
xi for 0 ≤ xi ≤ a
L
Mi =
P ( L − a ) xi − P ( xi − a) for a < xi ≤ L
L
P11.2. For the beam shown in Figure P11.2, determine the beam deflection,
y(x), by the finite difference method utilizing MATLAB’s inverse matrix
function or the MATLAB’s Gauss-Elimination method. Print the results in a
P
a
y
x
FIGURE P11.1
Deflection of a beam subjected to a concentrated load.
Boundary Value Problems of Ordinary Differential Equations 235
W2
W1
y
x
FIGURE P11.2
Deflection of a beam subjected to a linear increasing load.
table format. Also determine the approximate maximum deflection. Use the
following parameters:
Hint: The load can be considered as the sum of a uniform load and a trian-
gular load. For the triangular load, the resultant force equals ( w2 − w1 )L/2
located 2L/3 from the apex of the triangle. This results in the following
equation for M(x):
wL L w x2 x3
M( x) = 1 + (w2 − w1 ) x − 1 − (w2 − w1 )
2 6 2 6L
References
1. Bober, W., Introduction to Numerical and Analytical Methods with MATLAB for
Engineers and Scientists, CRC Press, Boca Raton, FL, 2014.
2. Bober, W., Stevens, A., Numerical and Analytical Methods with MATLAB for
Electrical Engineers, CRC Press, Boca Raton, FL, 2012.
Appendix: Greek Letters and Special
Characters in MATLAB® Plots
MATLAB® allows the use of Greek and special characters in its plot
headings and labels. The method for doing this is based on the TeX format-
ting language [1] and is summarized in this appendix.
MATLAB provides the functions title, xlabel, ylabel, and text for
adding labels to plots. These labels can include Greek and special characters
by applying the character sequences as shown in Table A.1. These sequences
all begin with the backslash character (\) and can be embedded in any
text string argument to title, xlabel, ylabel, and text. Subscripts
and superscripts may also be applied by using the _ and ^ operators. For
example, the sequence Vo is written as V_o and 106 is written as 10^6. If
the subscripts or superscripts are multiple characters, then use curly braces
to delimit the string to be subscripted, for example, Vout is generated with
V_{out}.
Example A.1
The following MATLAB script shows how to use special characters in a plot:
% Example_A_1.m
% This script shows example usage of special characters in MATLAB plots.
% Plot a 1MHz sine wave over the interval 0<t<2 microsec
t = 0:2e-8:2e-6;
fo = 1e6;
xout = sin(2*pi*fo*t);
plot(t*1e6,xout);
title('Plot of sin(2\pif_{o}t) for f_{o}=10^6 Hz');
xlabel('time (\museconds)');
ylabel('x_{out}(t)');
text(1.5,0.3,'\omega = 2\pi \times f_{o}');
----------------------------------------------------------------------------------------------
237
238 Appendix
TABLE A.1
Greek Letters
Greek Letter Greek Symbol
\alpha α
\beta β
\gamma γ
\delta δ
\epsilon ε
\zeta ζ
\eta η
\theta θ
\vartheta ϑ
\lambda λ
\mu μ
\nu ν
\rho ρ
\sigma σ
\tau τ
\phi ϕ
\omega ω
\Gamma Γ
\Delta Δ
\Phi Φ
\Omega Ω
Appendix 239
0.8
0.6
0.4
ω = 2π × fo
0.2
xout(t)
−0.2
−0.4
−0.6
−0.8
−1
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
time (μseconds)
FIGURE A.1
Example usage of Greek letters, special characters, subscripts and superscripts in a
MATLAB plot.
Reference
1. Knuth, D.E., The TeXbook, Addison Wesley, New York, 1984.
Review Answers
Review 1.1
1. List several ways engineers use the computer.
a. To solve mathematical models of physical phenomenon.
b. Storing and reducing experimental data.
c. Controlling machines.
d. Communicating with other engineers on a particular project.
2. List several areas of interest for engineers.
a. Designing new products.
b. Improve performance of existing products.
c. Improving manufacturing efficiency.
d. Minimizing costs of production.
e. Minimizing power consumption.
f. Research on developing new products.
3. List several methods that can be used in the design of new products.
a. Full-scale experiments.
b. Small-scale model experiments.
c. A mathematical model describing the phenomenon of interest.
4. Which method mentioned in item 3 is the least expensive?
The mathematical model is the least expensive.
5. List several components of a typical desktop/laptop computer system.
a. Input devices: keyboard, mouse, microphone.
b. Central processing unit consisting of a control unit, an arithmetic
logic unit and registers.
c. Memory and storage unit consisting of main memory which is
used for temporary storage of programs and data.
d. Secondary memory consisting of a hard drive, an optical drive
(a CD or a DVD), and a flash drive.
e. Output devices: monitor, printer, speakers.
f. Operating systems: Windows 10, MacOS, Linux.
6. Name several computer languages used today and in the past by
Engineers.
Fortran, C/C++, MATLAB, Pascal.
241
242 Review Answers
Review 2.1
1. What are the two alternative ways to start the MATLAB program?
If available, start the MATLAB program by double-clicking on the
MATLAB icon on the Window’s desktop. If not available,
a. For Windows versions earlier than Windows 10, go to the
Window’s Start menu, click on All Programs, find the MATLAB
program among the list of available programs and click on it.
This will open up the MATLAB desktop.
b. For Windows version 10, click on the Windows icon on the left
bottom of the screen and search for the MATLAB program and
click on it. This will open the MATLAB desktop.
2. What are the windows in the MATLAB’s default desktop?
The main windows are the Command Window, Current Folder, and
Workspace.
Review Answers 243
Review 2.2
1. List at least two conditions in selecting a name for a variable.
a. Variable name must start with a letter.
b. Variable names can only contain letters, numbers, and the under-
score character.
2. Finish the following statement. An arithmetic statement may
involve … constants, variables, arithmetic operators, and elementary
MATLAB functions and self-written functions.
3. What can be said about the variables that appear on the right side of
an arithmetic statement?
All variables on the right side of an arithmetic statement must be
previously defined (given a value) in the program.
244 Review Answers
Review 2.3
1. Name two commands that will result in printing to the screen.
a. fprintf()
b. display()
2. What is the command that will move the cursor to the next line?
\n.
3. What is the format that will print a floating point variable to 10
spaces and to three decimal points?
% 10.3f
4. What is the format that will print a floating point variable in scien-
tific notation to 12 spaces and to four decimal points?
% 12.4e
5. What are the commands necessary to print to a file?
a. fo=fopen('file_name','w');
b. fprintf(fo,'format \n',variables);
6. What is the command to create a linear plot of y versus x and what
type of variable must x and y be?
The command is plot(x,y);
Variables x and y must be vectors.
7. What are the commands that will label the x- and y-axis and provide
a title to a plot?
xlabel('x'), ylabel('y'), title('y vs. x')
Review 2.4
1. What is the objective in using a for loop?
The objective of a for loop is to repeat a series of statements with
just a few lines of code.
2. What is the syntax of a for loop?
for index variable = starting value: step size:
final value
3. Should table headings that are not to be repeated be inside a for
loop?
No.
246 Review Answers
Review 2.5
1. Name four commands that can be used in a script to input data into
the workspace. Also list where the data are located.
The commands that can be used to enter data into the work space are
load, fscanf, dlmread, and input. In the load, fscanf, and
dlmread commands, the data are located in a separate file, usually
a .txt file. For the input command, the data are entered from the
keyboard by the user.
2. Which of the four commands makes the program interactive?
The program becomes interactive with the input command.
The user is asked to enter values from the keyboard.
Review 2.6
1. When there is more than one function plotted on a graph, what are
the ways to identify which curve goes with which function?
Each curve can be given a different color, or a different line type.
In each case you can use the legend command to identify which
curve goes with which function. You can also use the text command
to label each of the curves.
2. What is the name of the function that will allow you to plot several
graphs on one page?
The name of the function that will allow you to plot several graphs on
one page is the subplot command. The subplot command is not a plot
command. It is used to position the several different plots on the page.
Review Answers 247
Review 3.1
1. What statement is frequently used to establish two conditional paths?
The if-else statements.
2. What series of statements is used to establish several conditional paths?
The if-elseif-else statements.
3. List the various types of logic statements that can be used with the
if–else and the if-elseif-else ladder.
a < b, a > b, a ≤ b, a ≥ b, a == b, a ~= b.
4. Is the else statement required with the if-else and with the
if-elseif-else ladder?
No.
5. What statement group and a MATLAB’s function are alternatives to
the if-elseif-else ladder?
The switch statement and MATLAB’s menu function.
Review 3.2
1. If y = 3.0 * A and A is a vector, what can you say about y?
If A = [a1 a2 a3 .... an ], then y = [ 3 × a1 3 × a2 3 × a3 .... 3 × an ].
2. If y = 3.0*sin(x) and x is a vector, what can you say about y.
If x = [x1 x2 x3 ..., xn ], then
y = [3 × sin( x1 ) 3 × sin( x2 ) 3 × sin( x3 ) ..., 3 × sin( xn )]
248 Review Answers
Review 4.1
1. When does it seem appropriate to write a self-written function?
If you have a complicated program and you wish to break it down into
smaller sections, it is appropriate to write a self-written function. Also,
if you have a program that requires a series of statements to be repeated
several time, it is convenient to place the series of statements in a self-
written function. Finally, many MATLAB functions require the user to
write a self-written function to describe the problem of interest.
2. In writing a self-written function what must be the first word in the
first executable statement?
The first word in the first executable statement in the function must
be function.
3. A self-written function usually has both an input and an output.
Where does the input come from? Where does the output go to?
The input comes from the calling program.
The output from the function goes to the calling program.
Review Answers 249
4. If a self-written function has more than one output, how must the
output be presented?
If a function has more than one output, the output must be in brackets.
5. How does a self-written function communicate with the calling
program?
The self-written function only communicates with the calling pro-
gram through the input and output variables. The exception is when
a global statement is contained in both the calling program and the
function.
6. What can be said about variables in the self-written function that are
not in the input or output arguments of the function and there are no
global statements?
If a variable in the function is not in the input or output arguments
of the function, then that variable is completely independent of vari-
ables in the calling program.
7. Do the variable names in the input and output arguments between
the calling program and the function have to be the same?
No, they only need to be in the same order.
8. If a programmer wishes to write a self-written function, but does
not wish to create an additional .m file, what can the programmer do
and what is the constraint?
The programmer can write an anonymous function, which is included
in the main program and not as a separate .m file. The constraint is
that it needs to be a single statement.
Review 5.1
1. Suppose you wish to assign a column vector consisting of string ele-
ments, what are the conditions that need to be followed in setting up
this column vector?
The conditions are (a) each string row needs to be enclosed by
single quotation marks, (b) each string row must have the same
number of columns, and (c) the entire matrix must be enclosed by
brackets.
2. Suppose that you had a data file that contains both numerical and
text data, what command would you use to read in the data into
your main program?
The command used to read in the data is the textscan command.
250 Review Answers
Review 6.1
1. What is meant by the term root of function f(x)?
The root of a function is the value of x that makes f(x) = 0
2. What is the objective in the search method for determining a root of
the equation f(x) = 0?
The objective of the search method is to find small intervals contain-
ing the roots.
3. What is the name of the MATLAB function for determining the roots
of a transcendental equation of the form f(x) = 0?
The name of MATLAB’s function to obtain the roots of a transcen-
dental equation is fzero.
4. In MATLAB’s function for determining the roots of a transcendental
equation, how does one define the function whose roots are to be
determined?
A self-written function should describe the function whose roots
are to be obtained. The name of this self-written function should be
entered as the first argument in MATLAB’s fzero function.
5. If you suspect that there is more than one real root, what method should
be used in combination with the MATLAB’s function to obtain the roots?
If you suspect that there is more than one root, you should use the
search method, in combination with MATLAB’s fzero function. The
search method is used to obtain a small interval in which a root lies and
MATLAB’s fzero function determines the root that lies in that interval.
6. If you are using the search method in combination with the fzero
function, what can you say about the second argument in the fzero
function?
The second argument to be entered in the fzero function should
be a vector of length 2 specifying the endpoints of the intervals that
contain the roots.
The functional values at the beginning and end of this interval
should differ in sign.
Review Answers 251
Review 7.1
1. Given a set of algebraic, linear equations in the form AX = C, where
A is the coefficient matrix and X and C are column vectors, what are
the two ways for solving for X in MATLAB?
a. X = inv(A)*C.
b. X = A\C.
2. Given a large system of algebraic, linear equations of the form
AX = C, describe the recommended approach to solving the system
of linear equations.
First we need to number each equation in the system. We then need
to determine the coefficients, ai , j , in each equation and the ci , where
the i represents the equation number and the j represents the num-
ber of the x variable associated with the coefficient.
Example:
Suppose we had a system of 10 equations requiring a coefficient
matrix, a(10, 10) and a c(10) matrix to solve the problem. Suppose the
7th equation was as follows:
and a(7 , 4) = −0.6, a(7 , 5) = −1, a(7 , 8) = 1, a(7 , 10) = 0.6, and c(7) = 0
After establishing all a(10, 10) and c(10) values use MATLAB’s inv
or MATLAB’s Gauss-Elimination function to solve the problem, that
is, X = inv(A)*C or X = A\C.
252 Review Answers
Review 8.1
1. Suppose an experiment produced a set of data and we wished to
create an approximating curve, yc , that is a polynomial expression
that best fits the data. What is the name of the MATLAB function
that will do this?
The name of MATLAB’s function that will do this is polyfit(x, y, m),
where (x, y) is the experimental data set and m is the degree of the
polynomial. The polyfit function returns the coefficients of the
polynomial, a1 , a2 ,..., am+1 where
Review 9.1
B
1. What is the formula for evaluating the integral, I = ∫A f ( x) dx by the
Simpson’s rule?
First sub-divide the x domain into N equal intervals, where N is an
even number giving x1 , x2 , x3 ,....., xN+1. Then determine the functional
values at the x positions giving f1 , f2 , f3 ,......., fN+1. The formula for the
integral by Simpson's rule is:
xN +1
∆x
I=
∫ f (x)dx ≈
x1
3
[ f1 + 4 f2 + 2 f3 + 4 f4 + 2 f5 + + 4 fN + fN +1 ]
Review 9.2
1. What is the name of MATLAB’s function for integrating a two-
dimensional function?
MATLAB’s function for integrating a two-dimensional function is
integral2.
2. List the arguments that go into MATLAB’s function for integrating a
two-dimensional function.
The arguments that go into MATLAB’s function for integrating a
two-dimensional function are
a. FUN(X,Y) which is a function handle for the function that
describes the two-dimensional function to be integrated.
b. XMIN, XMAX, YMIN, YMAX, where
XMIN ≤ X ≤ XMAX and YMIN ≤ Y ≤ YMAX
XMIN and XMAX are scalars and YMIN and YMAX may be scalars
or function handles.
Index
Note: Page numbers followed by f and t refer to figures and tables, respectively.
255
256 Index
E I
M template, 106f
textscan, 127–130
Machine language, 5
fundamentals, 9–80
Main Memory, 3
assignment operator, 19–21
MATLAB, 9
input, see Input, MATLAB
arithmetic operators, 244
loops, 36–50; see also Loops,
backslash operator, 154
MATLAB
colon operator (:), 28–29
overview, 9–10
command window, 20
simple plot commands, 34–36
computer programming, 1–8
variable names and types, 18–19
building blocks, 7
graphics, 55–69
computer programming, 3
bar charts, 63–65, 65f
computer usage, 1–2
figure command, 55–57
desktop/laptop computer system,
greek letters and mathematical
components, 3–4
symbols, 68
mathematical model, 2
hold on command, 59–61
methodologies, 6
interactively annotating plots, 69
needs, 5–6
multiple plots, 57–59
curve-fitting function, 169–174
pie charts, 65–68, 66f
cubic spline, 179–182
plotyy command, 62
desktop, 10–13
saving plots, 69
PLOTS tab, 34
subplot command, 63
windows, 11f, 12f
help window, 17f
features, commands, special items,
input command, 50
and built-in functions, 21–30
matrix, preallocation, 29
special values, 26–30
menu push button, 82f
trigonometric and other
ode45 function, 206, 215, 217
functions, 21–26
computer program, 220, 223
function(s), 26–27
syntax, 206
additional, 139
ODE, initial value problem, 206–214
built-in, 19, 133
“=” operator, 44
built-in ode45, 205
output, 30–34
cubic spline, 179
disp command, 31
dblquad, 194
fprintf command, 31–32
fminbnd, self-written function
printing to file, 32–34, 33f, 34f
and, 105–122
plots, greek letters and special
fzero, 131, 134–139, 145
characters in, 237–239,
Gauss-Elimination, 229, 234
238t, 239f
global, 136
program, 143, 149, 166–167
integral, 190–193
programming languages, 6–7
integral2, 194–204
script, 13–17, 14f, 15f, 237
interp1, 93–95, 179
version R2016A and R2016B, 54
inv, 154, 156, 229, 234
Matrix algebra, 153–154, 157
menu, 90–92
Memory cells, 4
myfun, 136
Memory/Storage Unit, 3
polyfit, 175, 184
menu function, 90–92
polyval, 170, 184
Moler, Cleve, Dr., 5
pulse(t), 224
mse function, 170
roots, 131, 139–141
258 Index
N Q
Network interface, 4 quad function, 190
Newton–Raphson method, 132
Numerical integration, 187–204
R
improper integrals, 190
MATLAB’s Registers, 3
integral2 function, 194–204 Resistive circuit problem, 159–161
integral function, 190–193 roots function, 133, 139–141
of ODE, 205–225 syntax, 139
initial value problem and
MATLAB’s, 206–214
S
overview, 205
and Simpson’s rule, 187–189 Scalar and vector operations, 96–99
Numerical methods, 2 addition, 96
element-by-element
operations, 96–98
O
scalar times vector multiplication, 96
ODE, see Ordinary differential two vector
equations (ODE) addition/subtraction, 96
ode45 function, 206, 219 functions operations, 98–99
ODEFUN function, 206 Search method, 132, 132f
Operating system (OS), 4 Secondary Memory, 4
Operators, 7 Self-written function, 105–110
Optical drive, 4 and MATLAB®’s fminbnd
Ordinary differential equations function, 105–122
(ODE), 205, 227 anonymous functions, 110–112
boundary value problems, 227–235 Self-written integrand function, 194
difference formulas, 227–235, 228t Simple plot commands, 34–36
overview, 227 Simpson’s rule, numerical integration
temperature, plot, 231f and, 187–189, 188f
numerical integration, 205–225 size() command, 154
initial value problem and spline function/method, 179
MATLAB’s, 206–214 sprintf command, 67
overview, 205 String specifiers, 128
OS (operating system), 4 subplot command, 63
Output devices, 4 Subscripts and superscripts, 237
switch command, 89–90
System software, 5
P
Pie charts, 65–68, 66f
T
plotyy command, 62
polyfit function, 169, 184 TeX formatting language, 237
MATLAB’s, 175 textscan function, 127–128
Polynomial regression, 169 Toolstrip, 10, 13–14
Programming languages, 26 open icon, 33
MATLAB, 6–7 print command, 32
overview, 5 save and run icon, 15f
Index 259