Spring 2021
CSC 113 Intro. To Programming with Matlab
Chapter 7
04/08/2021
Name:________________________
1. True or False. (4 points)
a. The input function can be used to read in scalars, vectors, or strings from the keyboard.
b. The disp function allows use of special format specifiers.
c. The sprintf function stores a formatted string in a string variable
d.
MATLAB will automatically detect and report logical errors in your program.
2. Explain what breakpoints are, and what the step button does. How they can be useful in program
debugging (4 points)?
3. An apple costs $0.75. A pear costs $1.25. Write MATLAB code to display this information in a
table with appropriate headers (5 points)
4. Write a MATLAB script file that: (12 points)
•
•
•
•
Stores the cost of an apple and a pair in variables (see #3)
Asks the user to enter how many apples and pears they want to buy.
Calculates the total price and displays the number of each fruit purchased and the price in
standard dollar and cent format; for example:
“The cost of 1 apple(s) and 1 pear(s) is $2.00.”
Extra Credit:
write a “receipt” of the transaction to a file, including the number and cost of
each fruit separate lines, along with the total cost (+5 points)
7.6 Debugging Your Codo 267
Editor. Cilhre\Mol?, DecurtinisGennal Matheb Book Films Mallab 9th Edition Chapter 71 Chapter 7 bumples EXAMPLE.I.M
х
an error on
Figure 7.13
Kapl with
Run och
Cou
Go To -
COITTI
doen
Bram
D.
"ne 13.
Funer1
2.1
Pro
EXAMPLE 7_1.m Checit), HomeSth Ed.10nm
ir 7 Thos We can be opened as a Live Script. For more information see Coating love scripts
1
88 Example 7.1
2
SFreefall
1
3 -
4
5
6
7-
8
9
10
clear, clc
88 Request input from the user
g input('What is the value of acceleration due to gravity?')
start = input('What starting time would you like?')
finish = input('What ending time would you like?')
incr = input('What time increments would you like calculated?')
time=start:incr:finish;
88 Calculate the distance
distance=1/2*g*time.^2;
O Line 13: Invalid syntax at end of line. Possibly, a ). lor) is missing.
&plot the results
loglog (time, distance
title ('Distance traveled in Freefall')
xlabel('time,s'),ylabel('distance, m')
88 Find the maximum distance traveled
final distance = max (distance)
11-
12
1
13
14 –
15
116
117-
scnpt
Ln 12
Col 18
7.6.2 Debugging Toolbar
When trying to find logic errors in a piece of code, it is often useful to run sections
of the program, then to stop, evaluate what has happened, and continue. Using sec-
tions is one way to accomplish this, but a more comprehensive approach is offered
by the debugging toolbar. It allows you to set breakpoints (places in the code where
the execution stops while you evaluate results) and to step through the code one
line at a time. Breakpoints can't be enabled until all of the syntax errors have been
resolved.
To set a breakpoint, click next to the line number on the left-hand side of the
editing window, or select the Set/Clear Breakpoint icon on the toolbar. A red circle
should appear, as shown in Figure 7.14. If the circle is gray, syntax errors still exist in
the program, or you have not saved the most recent version of the code.
When you run the program, the debugging toolbar is activated, the execu
tion will pause at the breakpoint, and the location will be marked with a gree
arrow (see Figure 7.15). To continue, select the continue icon from the breakpoin
toolbar.
You can also choose to step through the code one line at a time, using the si
icon. If your code includes calls to user-defined functions, you can step into
function, then step through the function code one line at a time, using the S
In icon. To leave the user-defined function, select the Step Out icon. For exan
Figure 7.16 shows a program that calls the user-defined function, RD. Both file
displayed in the editing window by selecting the VIEW tab, and choosing the
7.3 Graphical Inpul 259
Notice that the column names default to the variable names. You can specify more
meaningful column names by adding two additional fields
table (pig,d, 'VariableNames', ''Planet','g', 'Distanon's)
ans =
Planet
g
Distance
'Earth'
'Moon'
9.8
1.6
49000
8000
Finally, the output table would be cleaner without the ans = line. To accomplis?
this, nest the code inside the disp function
disp(table (p,g,d, 'VariableNames', {'Planet','g', 'Distance')))
which gives
Planet
g
Distance
'Earth'
'Moon'
9.8
1.6
49000
8000
* *
7.3 GRAPHICAL INPUT
MATLAB® offers a technique for entering ordered pairs of x- and y-values graphi-
cally. The ginput command allows the user to select points from a figure window
and converts the points into the appropriate x- and y-coordinates. In the statement
(x, y) = ginput(n)
MATLAB®
requests the user to select n points from the figure window. If the value
of n is not included, as in
[x, y] ginput
MATLAB® accepts points until the return key is entered
This technique is useful for picking points off a graph. Consider the graph in
Figure 7.4. The figure was created by defining x from 5 to 30 and calculating y:
x = 5:30;
y = x.^2 40.*x + 400;
plot(x, y)
axis ([5,30, -50,250])
The axis values were defined so that the graph would be easier to trace.
Once the ginput function has been executed, as in
[a,b] = ginput
MATLAB® adds a floating cross hair to the graph, as shown in Figure 7.4. After this
cross hair is positioned to the user's satisfaction, right-clicking and selecting Return
(Enter) sends the values of the x- and y-coordinates to the program:
a =
24.4412
b =
19.7368
258 Chapter 7 User-Controlled Input and Output
Figutz 1
OX
Eile Edit yien Insert Last Desktop Winden bele
od
Fore!
Ele Edit yo fresart Jook Desktop Winden Help
Ba
Range of a Projectile
1400
Range of a Projectile
The maumum ange was 1222 meters
1200
1200
The maxmum range was 1910 meters
1000
1000
800
800
Range, meters
Range, meters
500
600
400
400
200
200
0
0
0
0
10
20
30
60
70
80
90
10
20
30
60
40 50
Angle, degrees
40 50
Angle, degrees
70
80 9
Figure 7.3
The contents of the text box change, depending on the input to the program, and are controlled by the
sprintf function.
7.2.4 The table Function
Using disp and fprintf allows us to create tables of data in the command window,
but there is no easy way to create output where the table columns are different data
types, for example, characters and numbers. The table function actually uses a new
data type called a table to accomplish this. We will focus on how to use the table func-
tion to display output.
Consider a calculation where we want to know how far an object will fall
, both
on the earth and the moon, after 100 seconds. The acceleration due to gravity in
each location can be represented by a column vector, g:
g = [9.8; 1.6]
The distance travelled is one half the acceleration due to gravity times the time
squared, so
d = 0.5*g*100^2
which also returns a column vector.
We would like to have a table that lists the planet names in the first column, the
value of g in the second column, and the distance travelled in the third. To do this,
we need to define a column vector of planet names
p=( 'Earth'; 'Moon')
The p variable created in this way is actually a data type we haven't used much called
a cell array. Cell arrays are discussed in a later chapter. Once we've defined g, d and
p they can be combined to create the table using the table function (all of the
input vectors need to be columns.)
table (p.g,d)
which returns
ans
=
takes
2
h(1) =
suate this ſeature by doing the following:
a spacing of 7/100.
• Use the ginput function to estimate the maximum height the rocker
Plot the height of the rocket from 0 to 30 seconds, ana
7.17 The ginput function is useful for picking distances off a graph. Demon
• Use the disp command to report your results to the command window.
reaches and the time when the rocket hits the ground.
• Create a graph of a circle by defining an array of angles from 0 to 2 TT, with
• Use the ginput function to pick two points on the circumference of the
• Use hold on to keep the figure from refreshing, and plot a line between
Use the data from the points to calculate the length of the line between
them. (Hint: Use the Pythagorean theorem in your calculation.)
7.18 In recent years, the price of gasoline has fluctuated dramatically. Automobile
companies have responded with more fuel-efficient cars, in particular, hybrid
Camry rather than a Camry with a standard engine? The hybrid vehicles
the two points you picked.
are considerably more expensive, but get better gas mileage. Consider the
vehicle prices and gas efficiencies shown in Table P7.18.
Table P7.18 A Comparison of Standard and Hybrid Vehicles
Year
Model
Base
MSRP
Gas Efficiency, in-town/
highway (mpg)
2016
2016
Toyota Camry
Toyota Camry Hybrid IE
$23,070
$26,790
2016
2016
2016
2016
Toyota Highlander Limited
Toyota Highlander Limited Hybrid
Ford Fusion S
Ford Fusion S Hybrid
$40,915
$47,870
$22,120
$25,185
25/35
43/39 (hybrids may actually get beler
mileage in town than on the road)
20/25
28/28
23/34
43/41
One
way to compare two vehicles is to find the “cost to own.”
Cost to own = Purchase cost + Upkeep + Gasoline cost
parison we'll set them equal to zero.
Assume for this exercise that the upkeep costs are the same, so in our com
(a) What do you think the cost of gasoline will be over the next several years
(b) Find the "cost to own" as a function of the number of miles driven la
Prompt the user to enter an estimate of gasoline cost in dollars/gallon.
a pair of vehicles from the table, based on the fuel price estimate
from
1 times 6 is 6
2 times 6 is 12
3 times 6 is 18
an
:
7.10 Before calculators were readily available (about 1974), students used tabla
to determine the values of mathematical functions like sine, cosine, and
Create such a table for sine, using the following steps:
• Create a vector of angle values from 0 to 21 in increments of T/10.
• Calculate the sine of each of the angles, and group your results into
array that includes the angle and the sine.
• Use disp to create a title for the table, and a second disp command to
create column headings.
• Use the fprintf function to display the numbers. Display only two values
past the decimal point.
7.11 Very small dimensions—those on the atomic scale—are often measured in
angstroms. An angstrom is represented by the symbol Å and corresponde
to a length of 10-1° m. Create an inches-to-angstroms conversion table as
follows for values of inches from 1 to 10:
• Use disp to create a title and column headings.
• Use fprintf to display the numerical information.
• Because the length represented in angstroms is so big, represent your
result in scientific notation, showing two values after the decimal point
This corresponds to three significant figures (one before and two after
the decimal point).
7.12 Use your favorite Internet search engine and browser to identify
currency conversions for British pounds sterling, Japanese yen, and the
European euro to US dollars. Use the conversion tables to create the follow:
ing tables (use the disp and fprintf commands in your solution, which
should include a title, column labels, and formatted output):
(a) Generate a table of conversions from yen to dollars. Start the yen column
at 5 and increment by 5 yen. Print 25 lines in the table.
(b) Generate a table of conversions from the euros to dollars. Start the euro
column at 1 euro and increment by 2 euros. Print 30 lines in the table.
(c) Generate a table with four columns. The first should contain dollars, the
second the equivalent number of euros, the third the equivalent number
of pounds, and the fourth the equivalent number of yen. Let the dollar
column vary from 1 to 10.
recent
table
7.13 Consider the patient data contained in table P7.13.
Table P7.13 Patient Data
Patient Last Name Patient First Name
Age
Height (inches)
Weight (lb)
Fred
47
82
6
22
140
Smith
Jones
Webb
Anderson
Kathy
Milton
John
66
62
92
110
190
45
72
(a) Create a column vector of last names called last, using curly braces.
(b) Create a column vector of first names called first, using curly braces.
(c) Create column vectors for age, height and weight.
(d) Display the information using the table function.

Purchase answer to see full
attachment