100% found this document useful (69 votes)
205 views

Essentials of MATLAB Programming 3rd Edition Chapman Solutions Manual 1

The document discusses MATLAB programming concepts like branching statements, if/else structures, switch statements, and evaluating functions. It provides examples of MATLAB code for various tasks like determining package mailing costs, evaluating functions, and converting day names to numbers.

Uploaded by

kimberly
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (69 votes)
205 views

Essentials of MATLAB Programming 3rd Edition Chapman Solutions Manual 1

The document discusses MATLAB programming concepts like branching statements, if/else structures, switch statements, and evaluating functions. It provides examples of MATLAB code for various tasks like determining package mailing costs, evaluating functions, and converting day names to numbers.

Uploaded by

kimberly
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Essentials of MATLAB

Programming 3rd Edition


Chapman
Full download at link: https://testbankpack.com/p/solution-
manual-for-essentials-of-matlab-programming-3rd-edition-by-
chapman-isbn-1305970659-9781305970656/

4. Branching Statements and Program Design


4.1 (a) false (0) (b) false (0) (c) The first term (17 - pi < 15) is true (1), and the second term (pi
< 3) is false (0), so the xor function is true (1). (d) The true is converted to 1, and the false is
converted to 0, so the result of the expression true > false is true (1). (e) The expression (35
/ 17) is 2.0588. Therefore, the expression ~(35 / 17) is false (0), and the expression ~~(35
/ 17) is true (1). Since 1 ≠ 2.0588, the overall expression is false (0). (f) false (0) (g) true (1)

4.2 The if structure is:

% 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.

if temp < 97.5


disp('Temperature below normal');
59
© 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.
elseif temp > 103.0
disp('Temperature dangerously high');
elseif temp > 99.5
disp('Temperature slightly high');
elseif temp >= 97.5
disp('Temperature normal');
end

4.4 One possible mail program is shown below:

% Script file: mail.m


%
% Purpose:
% To calculate the cost of mail a parcel.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/18/15 S. J. Chapman Original code
%
% Define variables:

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)

% Prompt the user for the input power.


weight = input('Enter weight of parcel, in 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

When this program is executed, the results are:

» 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!

4.5 A version of funxy that uses nested if structures is shown below:

% Script file: funxy.m


%
% Purpose:
% This program solves the function f(x,y) for a
% user-specified x and y, where f(x,y) is defined as:
% _

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

% Prompt the user for the values x and y


x = input ('Enter the x coefficient: ');
y = input ('Enter the y coefficient: ');

% Calculate the function f(x,y) based upon


% the signs of x and y.
if x >= 0
if y >= 0
fun = x + y;
else
fun = x + x^2;
end
else
if y >= 0
fun = x^2 + y;
else
fun = x^2 + y^2;
end
end

% Write the value of the function.


disp (['The value of the function is ' num2str(fun)]);

4.6 A MATLAB program to evaluate the function y ( x ) = ln  1  is shown below:


 
1− x 
% Script file: eval_fn.m
%
% Purpose:
% This program evaluates a function, first checking
% to ensure that the input argument is legal.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/18/15 S. J. Chapman Original code

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

% Prompt the user for the value x


x = input ('Enter x: ');

% Calculate the function


if x < 1
fun = log( 1 / (1-x) );
disp(['log( 1 / (1-x) ) = ' num2str(fun)]);
else
disp('x must be < 1!');
end

When this program is executed, the results are:

» 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:

% Script file: day_of_week.m


%
% Purpose:
% To convert a string containing a day of week into the
% corresponding number.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/18/15 S. J. Chapman Original code
%
% Define variables:
% day -- Day of week (string)
% day_no -- Number of day

% Get name of day


day = input('Enter name of day: ','s');

% 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:

% Script file: select_course.m


%
% Purpose:
% To convert make a selection from a list of courses.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/18/15 S. J. Chapman Original code
%
% Define variables:
% course -- Course name (string)

% Get name of day


course = input('Select course ("English", "History", "Astronomy", or
"Literature"): ','s');

% 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:

% Script file: ideal_gas2.m


%
% Purpose:
% This program plots the pressure versus temperature of an
% ideal gas.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/18/15 S. J. Chapman Original code
%
% Define variables:
% n -- Number of atoms (mol)
% P -- Pressure (kPa)
% R -- Ideal gas constant (L kPa/mol K)
% T -- Temperature (K)
% V -- volume (L)

% Initialize nRT
n = 1; % Moles of atoms
R = 8.314; % Ideal gas constant
V = 10; % Volume of gas (L)

% Create array of input tempreatures.


T = 250:10:400;

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;

The resulting plot is

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:

% Script file: ideal_gas3.m


%
% Purpose:
% This program plots the pressure versus temperature of an
% ideal gas in a specific container.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/18/15 S. J. Chapman Original code
%
% Define variables:
% P1 -- Pressure at 0 deg C (kPa)
% P2 -- Pressure at another temperature (kPa)
% T1 -- Reference temperature 0 deg C = 273 K (K)
% T2 -- Temperature to calculate pressure for (K)

% Set reference temperature and pressure


T1 = 273;
P1 = 200;

% Create array of input tempreatures (K)


T2 = (0:10:200) + 273;

% 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:

4.11 For the ideal gas law

nRT (1 mol )( 8.314 L  kPa/mol  K )( 273 K )


P= = = 75.66 kPa
V1 30 L
For van der Waals equation,

nRT n2a
P= − 2
V − nb V

(1 mol )(8.314 L  kPa/mol  K )( 273 K ) (1 mol ) ( 0.396 kPa  L )


2

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:

% Script file: van_der_waals.m


%
% Purpose:
67
© 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.
% This program plots the pressure versus volume of an
% ideal gas according to the Ideal Gas Law and according
% to the van der Waals equation.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/18/15 S. J. Chapman Original code
%
% Define variables:
% n -- Number of atoms (mol)
% P1 -- Array of pressures (Ideal Gass Law) (kPa)
% P2 -- Array of pressures (van der Waals) (kPa)
% R -- Ideal gas constant (L kPa/mol K)
% T -- Temperature (K)
% V1 -- volume (L)

% 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 array of input volumes. Note that this


% array must be quite dense to catch the major
% changes in volume at low pressures.
V1 = logspace(-1,2,100);

% Calculate volumes according to Ideal Gas Law


P1 = (n * R * T) ./ V1;

% Calculate volumes according to van der Waals equation


P2 = ((n * R * T) ./ (V1 - n*b)) - (n^2*a./V1.^2);

% 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).

% Script file: ant_gain.m


%
% Purpose:
% This program plots an antenna gain pattern.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/20/15 S. J. Chapman Original code
%
% Define variables:

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

% Calculate gain versus angle


g = 0.5;
theta = -pi/2:pi/40:pi/2;
gain = abs(sin(4*theta)./(4*theta));

% Note that we must fix up the point where theta==0,


% since sinc(0) = 1, but numerically it becomes NaN.
gain(21) = 1;

% Plot gain
polar (theta,gain,'r-');
title ('\bfAntenna gain versus angle \theta');

The resulting plot is

4.15 A MATLAB program to calculate Australian taxes is shown below.

% Script file: calc_tax_2009.m


%
% Purpose:
% To calculate Australian income taxes for 2009.
%
% Record of revisions:
% Date Programmer Description of change

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

% Prompt the user for the input power.


income = input('Taxible income: $');

% Calculate basic tax


if income <= 6000
tax = 0;
elseif income <= 34000
tax = 0.15 * (income - 6000);
elseif income <= 80000
tax = 4200 + 0.30 * (income - 34000);
elseif income <= 180000
tax = 18000 + 0.40 * (income - 80000);
else
tax = 58000 + 0.45 * (income - 180000);
end

% Add Medicare Levy


tax = tax + 0.015 * income;

% Tell user
fprintf('Total tax for 2009 = $%.2f\n',tax);

When this program is executed, the results are as shown below.

>> 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.

% Script file: calc_tax_difference.m


%
% Purpose:
% To calculate Australian income taxes for 2002
% and 2009, and compare the difference.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================

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

% Prompt the user for the input power.


income = input('Taxible income: $');

% Calculate 2009 basic tax


if income <= 6000
tax2009 = 0;
elseif income <= 34000
tax2009 = 0.15 * (income - 6000);
elseif income <= 80000
tax2009 = 4200 + 0.30 * (income - 34000);
elseif income <= 180000
tax2009 = 18000 + 0.40 * (income - 80000);
else
tax2009 = 58000 + 0.45 * (income - 180000);
end

% Add Medicare Levy


tax2009 = tax2009 + 0.015 * income;

% Calculate 2002 basic tax


if income <= 6000
tax2002 = 0;
elseif income <= 20000
tax2002 = 0.17 * (income - 6000);
elseif income <= 50000
tax2002 = 2380 + 0.30 * (income - 20000);
elseif income <= 60000
tax2002 = 11380 + 0.42 * (income - 50000);
else
tax2002 = 15580 + 0.47 * (income - 60000);
end

% Add Medicare Levy


tax2002 = tax2002 + 0.015 * income;

% How much less tax was paid in 2009?


tax_diff = tax2002 - tax2009;

% Tell user
fprintf('Total tax for 2009 = $%.2f\n',tax2009);
fprintf('This is = $%.2f less than in 2002\n',tax_diff);

When this program is executed, the results are as shown below.

>> 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.

% Script file: refraction.m


%
% Purpose:
% To calculate the angle of incidence at which a light ray
% is refracted when passing from a medium with index of
% refraction n1 into a medium with index of refraction n2.
% The light ray is assumed to have an angle of incidence
% theta1 in the first medium, and the program calculates
% the angle of incidence theta2 in the second medium. Also,
% plot the incident and reflected rays.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/20/15 S. J. Chapman Original code
%
% Define variables:
% arg -- Argument of asin function
% n1 -- Index of refraction in medium 1
% n2 -- Index of refraction in medium 2
% theta1 -- Angle of incidence in medium 1
% theta2 -- Angle of incidence in medium 2

% Prompt the user for n1


n1 = input ('Enter index of refraction for medium 1: ');

% Prompt the user for n2


n2 = input ('Enter index of refraction for medium 2: ');

% Prompt the user for the angle of incidence in medium 1


theta1 = input ('Enter angle of incidence in medium 1 (degrees): ');

% Calculate the argument of the arcsin function


arg = ( n1 / n2 ) * sin( theta1 * pi/180 );

% Check for total reflection.


if abs(arg) > 1.0

% 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

% Get theta2 in degrees.


theta2 = asin( arg ) * 180 / pi;

% Tell user.
disp(['The angle of incidence in medium 2 is ' ...
num2str(theta2), ' degrees.']);

% Now plot the incident and reflected rays. We will


% create a plot whose size is [-1 1] in both the x
% and y directions, with the surface between the
% media at the line y = 0, and the incident ray
% striking the surface at the point (0,0).

% First, plot the boundary between the media.


figure(1);
plot([-1 1],[0 0],'k--','LineWidth',2);
hold on;

% Now plot the incident ray.


x(1) = -2 * sin(theta1 * pi/180);
y(1) = 2 * cos(theta1 * pi/180);
x(2) = 0;
y(2) = 0;
plot(x,y,'r-','LineWidth',2);

% Now plot the refracted ray.


x(1) = 0;
y(1) = 0;
x(2) = 2 * sin(theta2 * pi/180);
y(2) = -2 * cos(theta2 * pi/180);
plot(x,y,'b-','LineWidth',2);
title('\bfPlot of light refraction at a surface');
legend('Surface','Incident Ray','Refracted Ray');

% Finish up
hold off;
axis([-1 1 -1 1]);

end

When this program is executed, the results are:

» 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.

The plot for the first execution is shown below:

4.18 A program to calculate the amplitude and phase response of the high-pass filter is shown below:

% Script file: highpass_filter.m


%
% Purpose:
% This program plots amplitude and phase response
% of a highpass filter. It uses two subplots, on
% for amplitude and one for phase. The amplitude
% plot is log-log, and the phase plot is semilogx.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/20/15 S. J. Chapman Original code
%
% Define variables:
% amp -- Amplitude of complex function
% c -- Capacitance (farads)
% f -- Frequency (Hz)
% phase -- Phase of complex function
% r -- Resistance (ohms)
% vres -- Voltage response

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)

% Calculate frequency response


f = 1:100;
vres = (j*2*pi*f*r*c) ./ (1 + j*2*pi*f*r*c);

% Get amplitude and phase. Express phase in degrees.


amp = abs(vres);
phase = angle(vres) * 100/pi;

% Plot amplitude and phase vs frequency


figure(1)
subplot(2,1,1);
loglog (f,amp,'r-','LineWidth',2);
title ('\bfAmplitude and Phase versus frequency');
xlabel('\bfFrequency (Hz)');
ylabel('\bfAmplitude');
grid on;
subplot(2,1,2);
semilogx(f,phase,'r-','LineWidth',2);
xlabel('\bfFrequency (Hz)');
ylabel('\bfPhase (deg)');
grid on;

The resulting amplitude and phase responses are shown below:

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:

% Script file: read_file.m


%
% Purpose:
% This program prompts a user for a MAT file name, and
% reads data from that file. The file open lies in a
% try / catch structure to catch any errors, and allow
% the user to try again.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/20/15 S. J. Chapman Original code
%
% Define variables:
% filename -- Capacitance (farads)

% Clear any old data


clear all;

try

% Get the file name


filename = input('Enter file name: ','s');

% Read the file


load(filename)

catch

% If we get here, the file read failed. Tell user.


disp('File read failed. Try again...');

end

% If successful, display the names of the variables loaded


whos

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

filename 1x3 6 char

>> 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.

You might also like