Essentials of MATLAB Programming 3rd Edition Chapman Solutions Manual 1
Essentials of MATLAB Programming 3rd Edition Chapman Solutions Manual 1
% Convert to radians
theta_rad = theta * pi / 180;
% Calculate tangent
if abs(cos(theta_rad)) > 1E-20
tan = sin(theta_rad) / cos(theta_rad)
else
disp('Error: cos(theta) too small');
end
4.3 These statements will execute, but they will not produce the result that the programmer wanted. An
if/elseif/else structure will take the first valid branch, and ignore all others. Thus, if the
temperature is 105, the statement will display the message 'Temperature normal' instead of
the desired message. This problem can be fixed by restructuring the order of the statements. In
addition, the structure would not print out a message if the temperature were exactly 97.5. A
corrected version of the statements is shown below.
60
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% cost -- cost in dollars
% weight -- Weight of package (lbs)
% Calculate cost
if weight > 100
% Not mailable
disp('Packages heavier than 100 pounds cannot be mailed!');
else
if weight <= 2
cost = 15;
else
cost = 15 + (weight-2) * 5.00;
end
% Apply penalty
if weight > 70
cost = cost + 15;
end
% Display weight
fprintf('Cost = $%.2f\n',cost);
end
» mail
Enter weight of parcel, in lbs: 1
Cost = $15.00
» mail
Enter weight of parcel, in lbs: 10
Cost = $55.00
» mail
Enter weight of parcel, in lbs: 80
Cost = $420.00
» mail
Enter weight of parcel, in lbs: 120
Packages heavier than 100 pounds cannot be mailed!
60
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% |
% | x + y x >= 0 and y >= 0
% | x + y**2 x >= 0 and y < 0
% f(x,y) = | x**2 + y x < 0 and y >= 0
% | x**2 + y**2 x < 0 and y < 0
% |_
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 01/03/14 S. J. Chapman Original code
% 1. 03/18/15 S. J. Chapman Modified for nested ifs
%
% Define variables:
% x -- First independent variable
% y -- Second independent variable
% fun -- Resulting function
61
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
%
% Define variables:
% x -- First independent variable
% fun -- Resulting function
» eval_fn
Enter x: 2
x must be < 1!
» eval_fn
Enter x: 0
log( 1 / (1-x) ) = 0
» eval_fn
Enter x: -1
log( 1 / (1-x) ) = -0.69315
4.7 A program to convert a day name to a day number using a switch construct is shown below:
% Convert to number
switch (day)
case {'Sunday'},
day_no = 1;
case {'Monday'},
62
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
day_no = 2; case
{'Tuesday'},
day_no = 3;
case {'Wednesday'},
day_no = 4;
case {'Thursday'},
day_no = 5;
case {'Friday'},
day_no = 6;
case {'Saturday'},
day_no = 7;
otherwise,
disp(['Illegal day name: ' day '!']);
day_no = 0;
end
% Tell user
fprintf('Day number = %d\n',day_no);
When this program is executed, the results are as shown below. Note that the program handles the
case of incorrect day names.
>> day_of_week
Enter name of day: Sunday
Day number = 1
>> day_of_week
Enter name of day: Friday
Day number = 6
>> day_of_week
Enter name of day: Funday
Illegal day name: Funday!
Day number = 0
4.8 A program to convert a day name to a day number using a switch construct is shown below:
% Convert to number
63
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
switch (course)
case {'English'},
disp('English selected.');
case {'History'},
disp('History selected.');
case {'Astronomy'},
disp('Astronomy selected.');
case {'Literature'},
disp('Literature selected.');
otherwise,
disp(['Illegal course selected: ' course '!']);
end
When this program is executed, the results are as shown below. Note that the program handles the
case of incorrect course names.
» select_course
Select course ("English", "History", "Astronomy", or "Literature"):
English
English selected.
» select_course
Select course ("English", "History", "Astronomy", or "Literature"):
junk
Illegal course selected: junk!
4.9 A program to plot the pressure of an ideal gas as a function of temperature is shown below:
% Initialize nRT
n = 1; % Moles of atoms
R = 8.314; % Ideal gas constant
V = 10; % Volume of gas (L)
64
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Calculate pressures
P = (n * R * T) ./ V;
% Create plot
figure(1);
plot( T, P, 'r-', 'LineWidth', 2 );
title('\bfPressure vs Temperature in an Ideal Gas');
xlabel('\bfTemperature (K)');
ylabel('\bfPressure (kPa)');
grid on;
A linear / linear plot is most suitable for this plot because the scales of the two axes are similar, and
the total range is less than one order of magnitude.
4.10 This is another example of the ideal gas law PV = nRT , but this time we know the pressure at a
temperature of 0 C, and want to find the pressure at other temperatures. In this case, V, n and R are
constant, and the pressure at a temperature T2 can be found from the equation
P2V nRT2
=
P1V nRT1
P2 T2
=
P1 T1
65
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
T2
P P2 =
T1 1
Since we know that the pressure P1 = 200 kPa at T1 = 0 C = 273 K , the pressure at
T2 = 100 C = 373 K is
373 K
P2 = ( 200 kPa ) = 273.3 kPa
273 K
A MATLAB programs to plot the temperature versus pressure is shown below:
% Calculate pressures
P2 = (T2 ./ T1) * P1;
% Create plot
figure(1);
plot( T2, P2, 'r-', 'LineWidth', 2 );
title('\bfPressure vs Temperature in an Ideal Gas');
xlabel('\bfTemperature (K)');
ylabel('\bfPressure (kPa)');
grid on;
66
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
The resulting plot is shown below:
nRT n2a
P= − 2
V − nb V
P= −
( 30 L ) − (1 mol )( 0.0427 L/mol ) ( 30 L )
2
P = 75.765 kPa
A MATLAB program to plot the pressure vs volume for the Ideal Gas Law and van der Waals
equation is shown below:
% Initialize abnRTV
a = 0.396; % kPa-L
b = 0.0427; % L/mol
n = 1; % Moles of atoms
R = 8.314; % Ideal gas constant
T = 273; % Temperature (K)
V = 30; % Volume (L)
% Create plot
figure(1);
loglog( P1, V1, 'b--', 'LineWidth', 2 );
hold on;
loglog( P2, V1, 'r-', 'LineWidth', 2 );
hold off;
legend('Ideal Gas','van der Waals');
title('\bfPressure vs Volume');
xlabel('\bfPressure (kPa)');
ylabel('\bfVolume (L)');
grid on;
68
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
The resulting plot is shown below:
4.12 The switch construct decides which branch to execute based on the value of a single variable or
expression, and the values associated with each branch must be mutually exclusive. In contrast, the
control expressions for a nested if / else if / end construct can be different for each
branch, and the resulting conditions do not have to be mutually exclusive. In that case, the branch
with the first true control expression will be executed, and all others will be skipped.
4.13 Only the try branch of a try / catch construct is intended to be executed. The catch branch
is for error conditions only. All of the branches in other types of branching constructs can be
executed during normal program execution.
4.14 A MATLAB program to plot the antenna gain versus angle is shown below. Note that we have to
treat the angle 0 specially, since sinc 0 = 1, but mathematically sin(0) / 0 evaluates to NaN (not-a-
number).
69
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% gain -- Gain as a function of angle
% theta -- Angle from antenna axis
% Plot gain
polar (theta,gain,'r-');
title ('\bfAntenna gain versus angle \theta');
70
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% ==== ========== =====================
% 03/20/15 S. J. Chapman Original code
%
% Define variables:
% income -- Income in dollars
% tax -- Tax owed in dollars
% Tell user
fprintf('Total tax for 2009 = $%.2f\n',tax);
>> calc_tax_2009
Taxible income: $5000
Total tax for 2009 = $75.00
>> calc_tax_2009
Taxible income: $50000
Total tax for 2009 = $9750.00
>> calc_tax_2009
Taxible income: $100000
Total tax for 2009 = $27500.00
4.16 A MATLAB program to calculate how much less tax Australians paid in 2009 than in 2002 is
shown below.
71
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% 03/20/15 S. J. Chapman Original code
%
% Define variables:
% income -- Income in dollars
% tax2002 -- Tax 2002 owed in dollars
% tax2009 -- Tax 2009 owed in dollars
% Tell user
fprintf('Total tax for 2009 = $%.2f\n',tax2009);
fprintf('This is = $%.2f less than in 2002\n',tax_diff);
>> calc_tax_difference
72
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Taxible income: $5000
Total tax for 2009 = $75.00
This is = $0.00 less than in 2002
>> calc_tax_difference
Taxible income: $50000
Total tax for 2009 = $9750.00
This is = $2380.00 less than in 2002
>> calc_tax_difference
Taxible income: $100000
Total tax for 2009 = $27500.00
This is = $8380.00 less than in 2002
4.17 A MATLAB program to calculate the angle of refraction of a light ray is shown below.
% Tell user.
73
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
disp('This light ray is totally reflected.');
else
% Tell user.
disp(['The angle of incidence in medium 2 is ' ...
num2str(theta2), ' degrees.']);
% Finish up
hold off;
axis([-1 1 -1 1]);
end
» refraction
Enter index of refraction for medium 1: 1
Enter index of refraction for medium 2: 1.7
Enter angle of incidence in medium 1 (degrees): 45
The angle of incidence in medium 2 is 24.5789 degrees.
» refraction
Enter index of refraction for medium 1: 1.7
74
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Enter index of refraction for medium 2: 1
Enter angle of incidence in medium 1 (degrees): 45
This light ray is totally reflected.
4.18 A program to calculate the amplitude and phase response of the high-pass filter is shown below:
75
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Initialise filter values
r = 16000; % Resistance (ohms)
c = 1e-6; % Capacitance (farads)
76
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
4.19 A program to calculate the amplitude and phase response of the high-pass filter is shown below:
try
catch
end
To test this program, we will create a MAT file called datafile.mat, containing the two
variables a and b. When this program is executed, the results are:
» read_file
>> read_file
Enter file name: aaa
File read failed. Try again...
Name Size Bytes Class Attributes
>> read_file
Enter file name: datafile.mat
Name Size Bytes Class Attributes
77
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
a 1x10 80 double
b 1x10 80 double
filename 1x12 24 char
The variables a and b were read from the file when a valid file name was provided.
NOTE: When we study while loops in the next chapter, we will be able to improve this program so
that it keeps prompting the user for a valid file name, instead of just stopping. The improved
version of the program is called read_file_2.m, and it is available in the same directory as
read_file.m.
78
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.