Solutions Manual Matlab A Practical Introduction Programming Problem Solving 2nd Edition Stormy Attaway
Solutions Manual Matlab A Practical Introduction Programming Problem Solving 2nd Edition Stormy Attaway
Second Edition
SOLUTION MANUAL
Stormy Attaway
College of Engineering
Boston University
I. Introduction to Programming Using MATLAB
Exercises
2) Create a variable myage and store your age in it. Subtract one from the value of the
variable. Add two to the value of the variable.
3) Use the built-in function namelengthmax to find out the maximum number of
characters that you can have in an identifier name under your version of MATLAB.
>> namelengthmax
ans =
63
4) Explore the format command in more detail. Use help format to find options.
Experiment with format bank to display dollar values.
>> format +
>> 12.34
ans =
+
>> -123
ans =
-
>> format bank
>> 33.4
ans =
33.40
>> 52.435
ans =
52.44
5) Find a format option that would result in the following output format:
>> 5/16 + 2/7
ans =
67/112
6) Think about what the results would be for the following expressions, and then type them
in to verify your answers.
25 / 4 * 4
3 + 4 ^ 2
4 \ 12 + 4
3 ^ 2
(5 – 2) * 3
>> 25 / 4 * 4
ans =
25
>> 3 + 4 ^ 2
ans =
19
>> 4 \ 12 + 4
ans =
7
>> 3 ^ 2
ans =
9
>> (5 - 2) * 3
ans =
9
7) The combined resistance RT of three resistors R1, R2, and R3 in parallel is given by
1
RT =
1 1 1
R1 R2 R3
Create variables for the three resistors and store values in each, and then calculate the
combined resistance.
>> r1 = 3;
>> r2 = 2.2;
>> r3 = 1.5;
>> rt = 1/(1/r1 + 1/r2 + 1/r3)
rt =
0.6875
As the world becomes more “flat”, it is increasingly important for engineers and scientists
to be able to work with colleagues in other parts of the world. Correct conversion of data
from one system of units to another (for example, from the metric system to the American
system or vice versa) is critically important.
8) Create a variable pounds to store a weight in pounds. Convert this to kilograms and
assign the result to a variable kilos. The conversion factor is 1 kilogram = 2.2 pounds.
9) Create a variable ftemp to store a temperature in degrees Fahrenheit (F). Convert this to
degrees Celsius (C) and store the result in a variable ctemp. The conversion factor is C = (F
– 32) * 5/9.
10) Find another quantity to convert from one system of units to another.
11) The function sin calculates and returns the sine of an angle in radians. Use help elfun
to find the name of the function that returns the sine of an angle in degrees. Verify that
calling this function and passing 90 degrees to it results in 1.
>> sind(90)
ans =
1
12) A vector can be represented by its rectangular coordinates x and y or by its polar
coordinates r and . The relationship between them is given by the equations:
x = r * cos()
y = r * sin()
Assign values for the polar coordinates to variables r and theta. Then, using these values,
assign the corresponding rectangular coordinates to variables x and y.
>> r = 5;
>> theta = 0.5;
>> x = r * cos(theta)
x =
4.3879
>> y = r * sin(theta)
y =
2.3971
13) Wind often makes the air feel even colder than it is. The Wind Chill Factor (WCF)
measures how cold it feels with a given air temperature T (in degrees Fahrenheit) and
wind speed (V, in miles per hour). One formula for the WCF is:
WCF = 35.7 + 0.6 T – 35.7 (V 0.16) + 0.43 T (V 0.16)
Create variables for the temperature T and wind speed V, and then using this formula
calculate the WCF.
>> t = 20;
>> v = 11;
>> wcf = 35.7 + 0.6*t - 35.7*v^0.16+0.43*t*v^0.16
wcf =
7.9267
>> fix(3.5)
ans =
3
>> floor(3.5)
ans =
3
>> fix(3.4)
ans =
3
>> fix(-3.4)
ans =
-3
>> fix(3.2)
ans =
3
>> floor(3.2)
ans =
3
>> fix(-3.2)
ans =
-3
>> floor(-3.2)
ans =
-4
>> fix(-3.2)
ans =
-3
>> ceil(-3.2)
ans =
-3
19
sqrt(19)
31.2
3^1.2
tan()
tan(pi)
16) Use intmin and intmax to determine the range of values that can be stored in the types
uint32 and uint64.
>> intmin('uint32')
ans =
0
>> intmax('uint32')
ans =
4294967295
>> intmin('uint64')
ans =
0
>> intmax('uint64')
ans =
18446744073709551615
17) Are there equivalents to intmin and intmax for real number types? Use help to find
out.
>> realmin
ans =
2.2251e-308
>> realmin('double')
ans =
2.2251e-308
>> realmin('single')
ans =
1.1755e-38
>> realmax
ans =
1.7977e+308
18) Store a number with a decimal place in a double variable (the default). Convert the
variable to the type int32 and store the result in a new variable.
rand
real number in the range from 0 to 20
rand * 20
rand*(50-20)+20
round(rand * 10)
round(rand * 11)
round(rand*(100-50)+50)
20) Get into a new Command Window, and type rand to get a random real number. Make a
note of the number. Then, exit MATLAB and repeat this, again making a note of the random
number; it should be the same as before. Finally, exit MATLAB and again get into a new
Command Window. This time, change the seed before generating a random number; it
should be different.
>> rand
ans =
0.8147
>> rng('shuffle')
>> rand
ans =
0.4808
21) In the ASCII character encoding, the letters of the alphabet are in order: ‘a’ comes
before ‘b’ and also ‘A’ comes before ‘B’. However, which comes first - lower or uppercase
letters?
>> int32('a')
ans =
97
>> int32('A')
ans =
65
The upper case letters
>> char('xyz' + 2)
ans =
z{|
23) Using the colon operator, create the following row vectors
3 4 5 6
5 4 3 2
>> 3:6
ans =
3 4 5 6
>> 1:.5:3
ans =
1.0000 1.5000 2.0000 2.5000 3.0000
>> 5:-1:2
ans =
5 4 3 2
24) Using the linspace function, create the following row vectors
4 6 8
-3 -6 -9 -12 -15
9 7 5
>> linspace(4,8,3)
ans =
4 6 8
>> linspace(-3,-15,5)
ans =
-3 -6 -9 -12 -15
>> linspace(9,5,3)
ans =
9 7 5
25) Create the following row vectors twice, using linspace and using the colon operator:
1 2 3 4 5 6 7 8 9 10
>> 1:10
ans =
1 2 3 4 5 6 7 8 9 10
>> linspace(1,10,10)
ans =
1 2 3 4 5 6 7 8 9 10
2 7 12
>> 2:5:12
ans =
2 7 12
>> linspace(2,12,3)
ans =
2 7 12
26) Create a variable myend which stores a random integer in the range from 8 to 12.
Using the colon operator, create a vector that iterates from 1 to myend in steps of 3.
27) Using the colon operator and the transpose operator, create a column vector that has
the values -1 to 1 in steps of 0.2.
29) Create a vector variable vec; it can have any length. Then, write assignment statements
that would store the first half of the vector in one variable and the second half in another.
Make sure that your assignment statements are general, and work whether vec has an even
or odd number of elements (Hint: use a rounding function such as fix).
>> rand(2,3)
ans =
0.0215 0.7369 0.7125
0.7208 0.4168 0.1865
>> rand(2,3)*10
ans =
8.0863 2.2456 8.3067
2.9409 4.0221 5.0677
31) Create a variable rows that is a random integer in the range from 1 to 5. Create a
variable cols that is a random integer in the range from 1 to 5. Create a matrix of all zeros
with the dimensions given by the values of rows and cols.
33) Create a 2 x 3 matrix variable mymat. Pass this matrix variable to each of the following
functions and make sure you understand the result: fliplr, flipud, and rot90. In how many
different ways can you reshape it?
>> mat = randi([1,20], 2,3)
mat =
16 5 8
15 18 1
>> fliplr(mat)
ans =
8 5 16
1 18 15
>> flipud(mat)
ans =
15 18 1
16 5 8
>> rot90(mat)
ans =
8 1
5 18
16 15
>> rot90(rot90(mat))
ans =
1 18 15
8 5 16
>> reshape(mat,3,2)
ans =
16 18
15 8
5 1
>> reshape(mat,1,6)
ans =
16 15 5 18 8 1
>> reshape(mat,6,1)
ans =
16
15
5
18
8
1
34) Create a 4 x 2 matrix of all zeros and store it in a variable. Then, replace the second row
in the matrix with a vector consisting of a 3 and a 6.
35) Create a vector x which consists of 20 equally spaced points in the range from – to +.
Create a y vector which is sin(x).
>> x = linspace(-pi,pi,20);
>> y = sin(x);
36) Create a 3 x 5 matrix of random integers, each in the range from -5 to 5. Get the sign of
every element.
37) Create a 4 x 6 matrix of random integers, each in the range from -5 to 5; store it in a
variable. Create another matrix that stores for each element the absolute value of the
corresponding element in the original matrix.
38) Create a 3 x 5 matrix of random real numbers. Delete the third row.
>> mat = rand(3,5)
mat =
0.5226 0.9797 0.8757 0.0118 0.2987
0.8801 0.2714 0.7373 0.8939 0.6614
0.1730 0.2523 0.1365 0.1991 0.2844
>> mat(3,:) = []
mat =
0.5226 0.9797 0.8757 0.0118 0.2987
0.8801 0.2714 0.7373 0.8939 0.6614
39) Create a vector variable vec. Find as many expressions as you can that would refer to
the last element in the vector, without assuming that you know how many elements it has
(i.e., make your expressions general).
40) Create a matrix variable mat. Find as many expressions as you can that would refer to
the last element in the matrix, without assuming that you know how many elements or
rows or columns it has (i.e., make your expressions general).
42) The built-in function clock returns a vector that contains 6 elements: the first three are
the current date (year, month, day) and the last three represent the current time in hours,
minutes, and seconds. The seconds is a real number, but all others are integers. Store the
result from clock in a variable called myc. Then, store the first three elements from this
variable in a variable today and the last three elements in a variable now. Use the fix
function on the vector variable now to get just the integer part of the current time.
Exercises
1) Write a simple script that will calculate the volume of a hollow sphere,
4 3 3
(ro ri )
3
where ri is the inner radius and ro is the outer radius. Assign a value to a variable for the
inner radius, and also assign a value to another variable for the outer radius. Then, using
these variables, assign the volume to a third variable. Include comments in the script.
Ch2Ex1.m
% This script calculates the volume of a hollow sphere
2) The atomic weight is the weight of a mole of atoms of a chemical element. For example,
the atomic weight of oxygen is 15.9994 and the atomic weight of hydrogen is 1.0079. Write
a script that will calculate the molecular weight of hydrogen peroxide, which consists of
two atoms of hydrogen and two atoms of oxygen. Include comments in the script. Use
help to view the comment in your script.
Ch2Ex2.m
% Calculates the molecular weight of hydrogen peroxide
3) Write an input statement that will prompt the user for the name of a chemical element
as a string. Then, find the length of the string.
mat =
4 5 6
9 10 11
mat =
0 0
0 0
6) Experiment, in the Command Window, with using the fprintf function for real numbers.
Make a note of what happens for each. Use fprintf to print the real number 12345.6789.
realnum = 12345.6789;
7) Experiment, in the Command Window, with using the fprintf function for integers.
Make a note of what happens for each. Use fprintf to print the integer 12345.
intnum = 12345;
in a field width of 5
in a field width of 8
in a field width of 3
9) Write a script to prompt the user for the length and width of a rectangle, and print its
area with 2 decimal places. Put comments in the script.
Ch2Ex9.m
% Calculate the area of a rectangle
10) Write a script called echoname that will prompt the user for his or her name, and then
echo print the name in a sentence in the following format (use %s to print it):
>> echoname
What is your name? Susan
Wow, your name is Susan!
echoname.m
% Prompt the user and echo print name
11) Write a script called echostring that will prompt the user for a string, and will echo
print the string in quotes:
>> echostring
Enter your string: hi there
Your string was: 'hi there'
echostring.m
% Prompt the user and print a string in quotes
>> flowrate
Enter the flow in m^3/s: 15.2
A flow rate of 15.200 meters per sec
is equivalent to 542.857 feet per sec
flowrate.m
% Converts a flow rate from cubic meters per second
% to cubic feet per second
13) On average, people in a region spend 8% to 10% of their income on food. Write a script
that will prompt the user for an annual income. It will then print the range that would
typically be spent on food annually. Also, print a monthly range.
Ch2Ex13.m
% Calculates and prints the likely $ amount spent on food
% based on annual income
14) Wing loading, which is the airplane weight divided by the wing area, is an important
design factor in aeronautical engineering. Write a script that will prompt the user for the
weight of the aircraft in kilograms, and the wing area in meters squared, and will calculate
and print the wing loading of the aircraft in kilograms per square meter.
Ch2Ex14.m
% Calculates the wing loading for an airplane
% Prompt the user for the weight and wing area of the plane
plane_weight = input('Enter the weight of the airplane: ');
wing_area = input('Enter the wing area: ');
15) Write a script that assigns values for the x coordinate and then y coordinate of a point,
and then plots this using a green +.
Ch2Ex15.m
% Prompt the user for the coordinates of a point and plot
% the point using a green +
plot(x,y, 'g+')
16) Plot exp(x) for values of x ranging from -2 to 2 in steps of 0.1. Put an appropriate title
on the plot, and label the axes.
Ch2Ex16.m
% Plots exp(x)
x = -2:0.1:2;
y = exp(x);
plot(x,y,'*')
title('Exp(x)')
xlabel('x')
ylabel('exp(x)')
17) Create a vector x with values ranging from 1 to 100 in steps of 5. Create a vector y
which is the square root of each value in x. Plot these points. Now, use the bar function
instead of plot to get a bar chart instead.
Ch2Ex17.m
% Plots same x and y points using bar and plot
clf
x = 1:5:100;
y = sqrt(x);
plot(x,y,'*')
title('sqrt(x)')
figure(2)
bar(x,y)
title('sqrt(x)')
18) Create a y vector which stores random integers in the 1 to 100 range. Create an x
vector which iterates from 1 to the length of the y vector. Experiment with the plot
function using different colors, line types, and plot symbols.
Ch2Ex18.m
% Experiment with plot symbols and line types
y = randi([1, 100],1,15)
x = 1:length(y);
clf
plot(x,y,'rv')
figure(2)
plot(x,y,'g*:')
19) Plot sin(x) for x values ranging from 0 to (in separate Figure Windows):
using 10 points in this range
using 100 points in this range
Ch2Ex19.m
% Plots sin(x) with 10 points and 100 points in range 0 to pi
x = linspace(0,pi,10);
y = sin(x);
clf
figure(1)
plot(x,y,'k*')
title('sin(x) with 10 points')
figure(2)
x = linspace(0,pi);
y = sin(x);
plot(x,y,'k*')
title('sin(x) with 100 points')
20) Atmospheric properties such as temperature, air density, and air pressure are
important in aviation. Create a file that stores temperatures in degrees Kelvin at various
altitudes. The altitudes are in the first column and the temperatures in the second. For
example, it may look like this:
1000 288
2000 281
3000 269
5000 256
10000 223
Write a script that will load this data into a matrix, separate it into vectors, and then plot
the data with appropriate axis labels and a title.
Ch2Ex20.m
% Read altitudes and temperatures from a file and plot
load alttemps.dat
altitudes = alttemps(:,1);
temps = alttemps(:,2);
plot(altitudes,temps,'k*')
xlabel('Altitudes')
ylabel('Temperatures')
title('Atmospheric Data')
21) Create a 3 x 6 matrix of random integers, each in the range from 50 to 100. Write this
to a file called randfile.dat. Then, create a new matrix of random integers, but this time
make it a 2 x 6 matrix of random integers, each in the range from 50 to 100. Append this
matrix to the original file. Then, read the file in (which will be to a variable called randfile)
just to make sure that worked!
22) Create a file called “testtan.dat” comprised of two lines with three real numbers on
each line (some negative, some positive, in the -1 to 3 range). The file can be created from
the Editor, or saved from a matrix. Then, load the file into a matrix and calculate the
tangent of every element in the resulting matrix.
23) Write a function calcrectarea that will calculate and return the area of a rectangle. Pass
the length and width to the function as input arguments.
calcrectarea.m
function area = calcrectarea(length, width)
% This function calculates the area of a rectangle
% Format of call: calcrectarea(length, width)
% Returns the area
y = x3 – 4x2 + sin(x)
>> help fn
Calculates y as a function of x
>> y = fn(7)
y =
147.6570
fn.m
function out = fn(x)
% Calculates y as a function of x
25) Write a function mwh_to_gj that will convert from MWh to GJ. Here are some examples
of using the function.
>> disp(mwh_to_gj(1.1))
3.9600
mwh_to_gj.m
function out = mwh_to_gj(mwh)
% Converts from MWh to GJ
convertVel.m
function velmps = convertVel(velmph)
% Convert the velocity of an aircraft from
% miles per hour to meters per second
% Format of call: convertVel(mph)
% Returns velocity in mps
velmps = velmph/3600*5280*.3048;
end
27) If a certain amount of money (called the principal P) is invested in a bank account,
earning an interest rate i compounded annually, the total amount of money Tn that will be
in the account after n years is given by:
Tn = P (1 + i)n
Write a function that will receive input arguments for P, i, and n, and will return the total
amount of money Tn. Also, give an example of calling the function.
totMoney = p * (1+i)^n;
end
29) The velocity of a moving fluid can be found from the difference between the total and
static pressures Pt and Ps. For water, this is given by
Pt Ps
V = 1.016
Write a function that will receive as input arguments the total and static pressures and will
return the velocity of the water.
fluidvel.m
function waterVel = fluidvel(totp, statp)
% Calculates the velocity of water given the
% total and static pressures
% Format: fluidvel(total pressure, static pressure)
% Returns the velocity of the water
30) For a project, some biomedical engineering students are designing a device that will
monitor a person’s heart rate while on a treadmill. The device will let the subject know
when the target heart rate has been reached. A simple calculation of the target heart rate
(THR) for a moderately active person is
THR (220 A) * .6
where A is the person’s age. Write a function that will calculate and return the THR.
findthr.m
function thr = findthr(age)
% Calculate the target heart rate for
% a person of a given age
% Format of call: findthr(age)
% Returns target heart rate
stirling.m
function approxNFact = stirling(n)
% Approximate n! using Stirling's formula
% Format of call: stirling(n)
% Returns approximate factorial of n
mfgcost.m
% Prompts the user for the number of units, calls a function
% to calculate the cost for producing that many units, and
% prints this result
costn.m
function out = costn(n)
% Calculates the cost of manufacturing n
% units of a product
% Format of call: costn(n)
% Returns cost as 5*n^2-44*n+11
33) The conversion depends on the temperature and other factors, but an approximation is
that 1 inch of rain is equivalent to 6.5 inches of snow. Write a script that prompts the user
for the number of inches of rain, calls a function to return the equivalent amount of snow,
and prints this result. Write the function, as well!
Ch2Ex33.m
% Prompt the user for a number of inches of rain
% and call a function to calculate the
% equivalent amount of snow
rainToSnow.m
function outsnow = rainToSnow(rain)
% Calculate equivalent amount of snow
% given rainfall in inches
% Format of call: rainToSnow(rain)
% Returns equivalent snowfall
1
34) The volume V of a regular tetrahedron is given by V= 2 s3 where s is the length
12
of the sides of the equilateral triangles that form the faces of the tetrahedron. Write a
program to calculate such a volume. The program will consist of one script and one
function. The function will receive one input argument, which is the length of the sides, and
will return the volume of the tetrahedron. The script will prompt the user for the length of
the sides, call the function to calculate the volume, and print the result in a nice sentence
format. For simplicity, we will ignore units.
Ch2Ex34.m
% Calculates and prints the volume of a regular tetrahedron
% Prompts user for length of sides, calls a function to
% calculate the volume, and prints the result
tetVol.m
function vol = tetVol(len)
% Calculates the volume of a regular tetrahedron
% Format of call: tetVol(side length)
% Returns volume
35) Write a function that is called pickone, which will receive one input argument x ,which
is a vector, and will return one random element from the vector. For example,
>> pickone(4:7)
ans =
5
>> disp(pickone(-2:0))
-1
len = length(invec);
ran = randi([1, len]);
elem = invec(ran);
end
36) A function can return a vector as a result. Write a function vecout that will receive one
integer argument and will return a vector that increments from the value of the input
argument to its value plus 5, using the colon operator. For example,
>> vecout(4)
ans =
4 5 6 7 8 9
vecout.m
function outvec = vecout(innum)
% Create a vector from innum to innum + 5
% Format of call: vecout(input number)
% Returns a vector input num : input num+5
outvec = innum:innum+5;
end
37) If the lengths of two sides of a triangle and the angle between them are known, the
length of the third side can be calculated. Given the lengths of two sides (b and c) of a
triangle, and the angle between them α in degrees, the third side a is calculated as follows:
a2 = b2 + c2 – 2 b c cos(α)
Write a script thirdside that will prompt the user and read in values for b, c, and α (in
degrees), and then calculate and print the value of a with 3 decimal places. (Note: To
convert an angle from degrees to radians, multiply the angle by /180). The format of the
output from the script should look exactly like this:
>> thirdside
Enter the first side: 2.2
Enter the second side: 4.4
Enter the angle between them: 50
thirdside.m
% Calculates the third side of a triangle, given
% the lengths of two sides and the angle between them
38) A part is being turned on a lathe. The diameter of the part is supposed to be 20,000
mm. The diameter is measured every 10 minutes and the results are stored in a file called
partdiam.dat. Create a data file to simulate this. The file will store the time in minutes and
the diameter at each time. Plot the data.
partdiam.dat
0 25233
10 23432
20 21085
30 20374
40 20002
Ch2Ex38.m
% Read from a data file the diameter of a part every 10 minutes
% as it is turned on a lathe and plot this data
load partdiam.dat
mins = partdiam(:,1);
diams = partdiam(:,2);
plot(mins,diams,'k*')
xlabel('minutes')
ylabel('part diameter')
39) A file “floatnums.dat” has been created for use in an experiment. However, it contains
float (real) numbers and what is desired instead is integers. Also, the file is not exactly in
the correct format; the values are stored columnwise rather than rowwise. For example, if
the file contains the following:
91 13 91 63 10
28 55 96 96 16
97 96 49 80 14
Create the data file in the specified format. Write a script that would read from the file
floatnums.dat into a matrix, round the numbers, and write the matrix in the desired format
to a new file called intnums.dat.
Ch2Ex39.m
% Reads in float numbers stored column-wise from a file,
% rounds them to integers and writes row-wise to a new file
load floatnums.dat
inums = round(floatnums)';
save intnums.dat inums -ascii
40) A file called costssales.dat stores for a company some cost and sales figures for the last
n quarters (n is not defined ahead of time). The costs are in the first column, and the sales
are in the second column. For example, if five quarters were represented, there would be
five lines in the file, and it might look like this:
1100 800
1233 650
1111 1001
1222 1300
999 1221
Write a script called salescosts that will read the data from this file into a matrix. When
the script is executed, it will do three things. First, it will print how many quarters were
represented in the file, such as:
>> salescosts
There were 5 quarters in the file
Next, it will plot the costs using black circles and sales using black stars (*) in a Figure
Window with a legend (using default axes) as seen in Figure 2.8.
Company Costs and Sales
1300
Costs
Sales
1200
1100
1000
900
800
700
600
1 1.5 2 2.5 3 3.5 4 4.5 5
Quarter
Finally, the script will write the data to a new file called newfile.dat in a different order.
The sales will be the first row, and the costs will be the second row. For example, if the
file is as shown above, the resulting file will store the following:
800 650 1001 1300 1221
1100 1233 1111 1222 999
It should not be assumed that the number of lines in the file is known.
salescosts.m
load costssales.dat
costs = costssales(:,1);
sales = costssales(:,2);