George Mason University Table Data in Vectors or Matrices Programming Lab Report

The work is on MATLAB.

Save Time On Research and Writing
Hire a Pro to Write You a 100% Plagiarism-Free Paper.
Get My Paper

Exercises are:

  • 8.3: You must store the table data in vectors or matrices before processing
  • 8.14
  • 8.18
  • 8.20

Problems 349
almost undoubtedly need to cancel the execution of this loop because of
the large amount of time it takes. Recall that Ctrl c terminates the program.
(d) If you are going to use a constant value several times in a for loop,
calculate it once and store it, rather than calculating it each time
through the loop. Demonstrate the increase in speed of this process
by adding (sin(0.3) + cos (pi/3)) *5! to every value in the
long vector in a for loop. (Recall that ! means factorial, which can be
calculated with the MATLAB® function factorial.)
(e) As discussed in this chapter, if MATLAB® must increase the size of a
vector every time through a loop, the process will take more time than
if the vector were already the appropriate size. Demonstrate this fact by
repeating part (b) of this problem. Create the following vector of y-values,
in which every element is equal to zero before you enter the for loop:
y = zeros (1,100000);
You will be replacing the zeros one at a time as you repeat
the
calculations in the loop.
Challenge Problems
9.20 (a) Create a function called polygon that draws a polygon in a polar plot.
Your function should have a single input parameter—the number of
sides.
(b) Use a for loop to create a figure with four subplots, showing a triangle
in the first subplot, a square in the second subplot, a pentagon in the
third subplot, and a hexagon in the fourth subplot. You should use the
function you created in part (a) to draw each polygon. Use the index
parameter from the for loop to specify the subplot in which each
polygon is drawn, and in an expression to determine the number of
sides used as input to the polygon function.
9.21 Consider the following method to approximate the mathematical constant,
e. Start by generating Kuniform random integers between 1 and K. Compute
J, the number of integers between 1 and K, which were never generated. We
then approximate e by the ratio
K
J
Consider the following example for K=5. Assume that the following five
integers are randomly generated between 1 and 5.
1 1 2 3 2
The number of times the integers are generated is given by
Integers
2 3 4 5
Number of instances 2 2 1 0 0
In this example, there are two integers, namely 4 and 5, which were never
generated. This means that J= 2. Consequently, e is approximated by
5
2.5
2
Problems 345
MATLAB® SUMMARY
Commands and Functions
break
clock
continue
end
error
etime
causes the execution of a loop to be terminated
determines the current time on the CPU clock
terminates the current pass through a loop, but proceeds to the next pass
identifies the end of a control structure
terminates the program and sends a message to the screen
finds elapsed time
generates a loop structure
creates a matrix of ones
starts a timing sequence
stops a timing sequence
generates a loop structure
for
ones
tic
toc
while
KEY TERMS
converge
diverge
for loop
infinite loop
loop
repetition
midpoint break loop
nested loops
while loop
series
vectorization
PROBLEMS
9.1 Use a for loop to sum the elements in the following vector:
x= [1, 23, 43, 72, 87, 56, 98, 33]
Check your answer with the sum function.
9.2 Repeat the previous problem, this time using a while loop.
9.3 Use a for loop to create a vector of the squares of the numbers 1 through 5.
9.4 Use a while loop to create a vector of the squares of the numbers 1 through 5.
9.5 Use the primes function to create a list of all the primes below 100. Now
use a for loop to multiply adjacent values together. For example, the first
four prime numbers are
2 3 5 7.
Your calculation would be
2*3 3*5 5*7
which gives
6 15 35.
9.6
A Fibonacci sequence is composed of elements created by adding the two
previous elements. The simplest Fibonacci sequence starts with 1, 1, and
proceeds as follows:
1, 1, 2, 3, 5, 8, 13,
Problems 347
Because of interest payments and your contribution, each month your
balance will increase in accordance with the formula
new balance = old balance + interest +
your
contribution
Use a for loop to find the amount in the savings account each month for
the next 18 years. (Create a vector of values.) Plot the amount in the account
as a function of time. (Plot time on the horizontal axis, and dollars on the
vertical axis.)
9.11 Imagine that you have a crystal ball and can predict the percentage increases
in tuition for the next 22 years. The following vector increase shows your
predictions, in percent, for each year:
increase = [10, 8, 10, 16, 15, 4, 6, 7, 8, 10, 8, 12,
14, 15, 8, 7, 6, 5, 7, 8, 9, 8]
Use a for loop to determine the cost of a four-year education, assuming that
the current cost for one year at a state school is $7000.
9.12 Use an if statement to compare your results from the previous two prob-
lems. Are you saving enough? Send an appropriate message to the command
window.
9.13 Edmond Halley (the astronomer famous for discovering Halley’s comet)
invented a fast algorithm for computing the square root of a number, A.
Halley’s algorithm approximates V A as follows:
Start with an initial guess xį. The new approximation is then given by
1
Yn
n
xn
Xn+1 +(15 – yn(10 – 3yn))
8
These two calculations are repeated until some convergence criterion, ε, is met.
| *n+1 – xn! Se
Write a MATLAB® function called my_sqrt that approximates the square
root of a number. It should have two inputs, the initial guess and the conver-
gence criterion.
Test your function by approximating the square root of 5 and comparing
it to the value calculated with the built-in MATLAB® function, sqrt.
9.14 The value of cos(x) can be approximated using a Maclaurin series
X
+
cos(x) = 1 – +
2! 4! 6!
which can be expressed more compactly as
x(k-1)*2
k=1
=1(-1)k-1
((k-1)*2)!
(recall that the symbol ! stands for factorial).
Use a midpoint break loop to determine how many terms must be
included in the summation, in order to find the correct value of cos(2)
within an error of.001. Limit the number of iterations to a maximum of 10.
9.15 The value of sin(x) can be approximated as
23 25 27
sin(x)
+
3! 5! 7!
= X –
+
346 Chapter 9 Repetition Structures
However, a Fibonacci sequence can be created with any two starting num-
bers. Fibonacci sequences appear regularly in nature. For example, the shell
of the chambered nautilus (see Figure P9.6) grows in accordance with a
Fibonacci sequence.
Prompt the user to enter the first two numbers in a Fibonacci sequence,
and the total number of elements requested for the sequence. Find the
sequence and store it in an array by using a for loop. Now plot your results
on a polarplot graph. Use the element number for the angle, and the
value of the element in the sequence for the radius.
9.7 Repeat the preceding problem, this time using a while loop.
9.8 One interesting property of a Fibonacci sequence is that the ratio of the
values of adjacent members of the sequence approaches a number called
“the golden ratio” or 0 (phi). Create a program that accepts the first two
numbers of a Fibonacci sequence as user input, then calculates additional
values in the sequence until the ratio of adjacent values converges to
within 0.001. You can do this in a while loop by comparing the ratio of
Figure P9.6
Chambered nautilus.
(Colin Keates © Dorling
Kindersley, Courtesy of the
natural history museum,
London.)
11
Chapter 9 Repetition Structures
Write a function called eapprox that takes the value of K as input, and
which then approximates e using the method described above. Test your
function several times with different values of K, and compare the result to
the value of e calculated using the built-in MATLAB® function.
exp(1)
HINT
Use the randi function to create an array of random integers.
9.22 Vectorize (replace loops with a single statement) the calculations in the
function created in the previous problem, by using the built-in MATLAB®
functions histcounts and sum.
Problems 307
}
Figure P8.3
Solid-fuel rocket booster
to a Titan missile. (NASA
Headquarters)
(g) Use the max function to determine the maximum temperature reached
and the time at which it occurred.
8.2 The height of a rocket (in meters) can be represented by the following
equation:
height = 2.1312 – 0.001314 +0.000034 14.751
Create a vector of time (1) values from 0 to 100 at 2-second intervals.
(a) Use the find function to determine when the rocket hits the ground
to within 2 seconds. (Hint: The value of height will be positive for all
values until the rocket hits the ground.)
(b) Use the max function to determine the maximum height of the rocket
and the corresponding time.
(c) Create a plot with t on the horizontal axis and height on the vertical axis
for times until the rocket hits the ground. Be sure to add a title and axis
labels.*
8.3 Solid-fuel rocket engines are used as boosters for the space shuttle, in satellite
launch vehicles, and in weapons systems (see Figure P8.3). The propellant is
a solid combination of fuel and oxidizer, about the consistency of an eraser.
For the space shuttle, the fuel component is aluminum and the oxidizer
is ammonium perchlorate, held together with an epoxy resin “glue.” The
propellant mixture is poured into a motor case, and the resin is allowed to
cure under controlled conditions. Because the engines are extremely large,
they are cast in segments, each requiring several “batches” of propellant
to fill. (Each engine contains over 1.1 million pounds of propellant!) This
casting-curing process is sensitive to temperature, humidity, and pressure.
If the conditions aren’t just right, the fuel could ignite or the properties of
the propellant grain (which means its shape; the term grain is borrowed
from artillery) might be degraded. Solid-fuel rocket engines are extremely
expensive as well as dangerous and clearly must work right every time, or
the results will be disastrous. Failures can cause loss of human life and irre-
placeable scientific data and equipment. Highly public failures can destroy
a company. Actual processes are tightly monitored and controlled. However,
for our purposes, consider these general criteria:
The temperature should remain between 115°F and 125°F.
The humidity should remain between 40% and 60%.
The pressure should remain between 100 and 200 Torr.
Imagine that the data in Table P8.3 were collected during a casting-curing
process.
Table P8.3 Casting-Curing Data
Batch Number
Temperature (°F)
Humidity (%)
116
45
42
1530
1240
2380
1470
3590
Pressure (Torr)
110
115
120
95
114
118
124
126
41
38
61
118
Source: Pearson Education
*From Etter, Kuncicky, and Moore, Introduction to Matlab 7 (Upper Saddle River, NJ: Pearson/Prentice
Hall, 2005).
308 Chapter 8 logical Functions and Selection Structures
(a) Use the find command to determine which batches did and did not
meet the criterion for temperature.
(b) Use the find command to determine which batches did and did not
meet the criterion for humidity.
(c) Use the find command to determine which batches did and did not
meet the criterion for pressure.
(d) Use the find command to determine which batches failed for
son and which passed.
(e) Use your results from the previous questions, along with the length
command, to determine what percentage of engines passed or failed on
the basis of each criterion and to determine the total passing rate.
8.4 Two gymnasts are competing with each other. Their scores are shown in
Table P8.4.
any rea-
Table P8.4 Gymnastics Scores
Event
Gymnast 1
Gymnast 2
Pommel horse
Vault
Floor
Rings
9.821
9.923
9.624
9.432
9.534
9.203
9.700
9.925
9.83
9.987
9.354
9.879
High bar
Parallel bars
8.5
8.6
(a) Write a program that uses find to determine how many events each
gymnast won.
(b) Use the mean function to determine each gymnast’s average score.
Use find to create a function called f that satisfies the following criteria:
For values of x > 2,5(x) = x2
For values of x = 2, f(x) = 2x
Plot your results for values of x from – 3 to 5. Choose your spacing to create a
smooth curve. You should notice a break in the curve at x= 2. What happens
if you try to do this problem using an if/else structure.
Create a function called g that satisfies the following criteria:
For x-1 and x ST, g(x) = cos(x)
For x>T,
g(x) = -1
Plot
your
results for values of x from – 27 to +27. Choose your spacing to
create a smooth curve.
A file named temp.dat contains information collected from a set of thermocou-
ples. The data in the file are shown in Table P8.7. The first column consists of
time measurements (one for each hour of the day), and the remaining columns
correspond to temperature measurements at different points in a process.
(a) Write a program that prints the index numbers (rows and columns) of
temperature data values greater than 85.0. (Hint: You’ll need to use the
find command.)
(b) Find the index numbers (rows and columns) of temperature data values
less than 65.0.
8.7
Problems 315
Suppose the Quality Widget Company has the savings plan described
in Table P8.16. Create a function that finds the total yearly contribution to
your savings plan, based on your salary and the percentage you contribute.
Remember, the total contribution consists of the employee contribution and
the company
contribution.
SWITCH/CASE
Table P8.16 Quality Widget Company Savings Plan
Income
Maximum You Can
Save Tax Free
Maximum the Company
Will Match
Up to $30,000
Between $30,000
and $60,000
Between $60,000
and $100,000
10%
10%
10%
10% of the first $30,000 and 5% of
the amount above $30,000
10% of the first $60,000 and 8% of 10% of the first $30,000 and 5% of
the amount above $60,000 the amount between $30,000 and
$60,000; nothing for the remainder
above $60,000
10% of the first $60,000 and 8% of Nothing – highly compensated
the amount between $60,000 and employees are exempt from this
$100,000; nothing on the amount plan and participate in stock options
above $100,000
instead
Above $100,000
AO
oo
8.17 In order to have a closed geometric figure composed of straight lines
(see Figure P8.17), the angles in the figure must add to
(n-2)(180 degrees)
where n is the number of sides.
(a) Prove this statement to yourself by creating a vector called n from 3 to
6 and calculating the angle sum from the formula. Compare what you
know about geometry with your answer.
(b) Write a program that prompts the user to enter one of the following:
triangle
square
pentagon
hexagon
Use the input to define the value of n via a switch/case structure;
then use n to calculate the sum of the interior angles in the figure.
(c) Reformulate your program from part (b) so that it uses a menu.
8.18 At a local university, each engineering major requires a different number of
credits for graduation. For example, recently the requirements were as follows:
figure P8.17
Regular polygons.
Civil Engineering
Chemical Engineering
Computer Engineering
Electrical Engineering
Mechanical Engineering
130
130
122
126.5
129
Prompt the user to select an engineering program from a menu. Use a
switch/case structure to send the minimum number of credits required
for graduation back to the command window.
314 Chapter 8 Logical Functions and Selection Structures
8.13 The inverse sine (asin) and inverse cosine (acos) functions are valid only
for inputs between – 1 and +1, because both the sine and the cosine have
values only between – 1 and +1 (see Figure P8.13). MATLAB® interprets the
result of asin or acos for a value outside the range as a complex number.
For example, we might have
acos (-2)
ans
3.1416

1.3170i
which is a questionable mathematical result. Create a function called my
asin that accepts a single value of x and checks to see if it is between – 1
and +1 (-1< = x < = 1). If x is outside the range, send an error message to the screen. If it is inside the allowable range, return the value of asin. The sine function 2 1.5 Figure P8.13 The sine function varies between - 1 and +1. Thus, the inverse sine (asin) is not defined for values greater than 1 and values less than -1. 1 0.5 (x)uis 0 m -0.5 -1.5 -2 10-8 -6 -4 -2 2 4 6 8 10 0 angle saws = 8.14 Create a program that prompts the user to enter a scalar value for the outside air temperature. If the temperature is equal to or above 80°F, send a message to the command window telling the user to wear shorts. If the temperature is between 60°F and 80°F, send a message to the command window telling the user that it is a beautiful day. If the temperature is equal to or below 60°F, send a message to the command window telling the user to wear a jacket or coat. 8.15 Suppose the following matrix represents the number of saws ordered from your company each month over the last year: [1,4,5,3,7,5,3,10,12,8,7,4] All the numbers should be zero or positive. (a) Use an if statement to check whether any of the values in the matrix are invalid. (Evaluate the whole matrix at once in a single if statement.) Send the message “All valid” or else “Invalid number found” to the screen, depending on the results of your analysis. (b) Change the saws matrix to include at least one negative number, and check your program to make sure that it works for both cases. 8.16 Most large companies encourage employees to save by matching their con- tributions to a 401(k) plan. The government limits how much you can save in these plans, because they shelter income from taxes until the money is withdrawn during your retirement. The amount you can save is tied to your income, as is the amount your employer can contribute. The government will allow you to save additional amounts without the tax benefit. These plans change from year to year, so this example is just a made-up “what if.” Problems 317 Prompt the user to specify either a five-pointed or a six-pointed star, using a menu. Then create the star in a MATLAB® figure window. Note that a six- pointed star is made of three triangles and requires a strategy different from that used to create a five-pointed star. CHALLENGE PROBLEMS 8.20 Most major airports have separate lots for long-term and short-term park- ing. The cost to park depends on the lot you select, and how long you stay. Consider this rate structure from the Salt Lake International Airport during the summer of 2016. • Long-Term (Economy) Parking o The first hour is $2.00, and each additional hour or fraction thereof is $1.00 o Daily maximum $9.00 o Weekly maximum $60.00 • Short-Term Parking o The first 30 minutes are $2.00 and each additional 20 minutes or fraction thereof is $1.00 o Daily maximum $32.00 Write a program that asks the user the following: • Which lot are you using? How many weeks, hours, days, and minutes did you park? Your program should then calculate the parking bill.

Still stressed from student homework?
Get quality assistance from academic writers!

Order your essay today and save 25% with the discount code LAVENDER