Professional Documents
Culture Documents
80
© 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:
5.2 The MATLAB statements to evaluate the expression with vectors are
5.3 The MATLAB statements to print a table of the even numbers between 0 and 50 and their squares
are
% Create headings
fprintf(' Value Square \n');
fprintf(' ====== =========\n');
» squares
Value Square
81
© 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.
====== =========
0 0
2 4
4 16
...
...
48 2304
50 2500
% Calculate as vectors
x = -1:0.1:3;
y = x.^2 - 3*x + 2;
% Plot function
figure(1);
plot( x, y, 'r--', 'LineWidth',3);
title('\bfPlot of \ity(x) \rm\bf vs \itx');
xlabel('\bf\itx');
ylabel('\bf\ity(x)');
82
© 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:
% Get n
n = input('Enter n: ');
elseif round(n) ~= n
83
© 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('Error--n must be an integer!');
else
% Calculate n!
if n == 0
fact = 1;
else
fact = 1;
for ii = 1:n
fact = fact * ii;
end
end
% Display result
disp([int2str(n) '! = ' int2str(fact)]);
end
» factorial
Enter n: -4
Error--n must be non-negative!
» factorial
Enter n: 1.4
Error--n must be an integer!
» factorial
Enter n: 5
5! = 120
5.6 (a) 65536 times. The loop index values will be -32768, -32767, …, -1, 0, 1, …, 32767. (b) 0 times
1
1
(c) 1 time, with the loop index value = 2 (d) 5 times, with the loop index values being 1 each
1
1
time.
5.7 (a) ires = 21; loop executes 21 times; (b) ires = 22; loop executes 4 times (c) ires = 18;
loop executes 3 times (d) ires = 24; outer loop executes 4 times, and inner loop executes 11
times.
5.8 (a) ires = 10; loop executes 9 times (b) ires = 256; loop executes 3 times (c) ires = 2; loop
never executes.
1 −2 3 −4 0 0 0 0
5.11 A modified version of ball.m with vectorized inner loops is shown below.
% Constants
conv = pi / 180; % Degrees-to-radians conversion factor
g = -9.81; % Accel. due to gravity
vo = 20; % Initial velocity
85
© 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.
% Write out table of ranges
fprintf ('Range versus angle theta:\n');
for ii = 1:91
theta = ii - 1;
fprintf(' %2d %8.4f\n',theta, range(ii));
end
5.12 A modified version of ball.m that allows the user to specify the acceleration due to gravity is
shown below.
86
© 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.
% Script file: ball.m
%
% Purpose:
% This program calculates the distance traveled by a ball
% thrown at a specified angle "theta" and a specified
% velocity "vo" from a point on the surface of the Earth,
% ignoring air friction and the Earth's curvature. It
% calculates the angle yielding maximum range, and also
% plots selected trajectories.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 01/30/14 S. J. Chapman Original code
% 1. 03/27/15 S. J. Chapman Modified to read g
%
% Define variables:
% conv -- Degrees to radians conv factor
% gravity -- Accel. due to gravity (m/s^2)
% ii, jj -- Loop index
% index -- Location of maximum range in array
% maxangle -- Angle that gives maximum range (deg)
% maxrange -- Maximum range (m)
% range -- Range for a particular angle (m)
% time -- Time (s)
% theta -- Initial angle (deg)
% traj_time -- Total trajectory time (s)
% vo -- Initial velocity (m/s)
% vxo -- X-component of initial velocity (m/s)
% vyo -- Y-component of initial velocity (m/s)
% x -- X-position of ball (m)
% y -- Y-position of ball (m)
% Constants
conv = pi / 180; % Degrees-to-radians conversion factor
vo = 20; % Initial velocity
87
© 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.
% Write out table of ranges
fprintf ('Range versus angle theta:\n');
for ii = 1:91
theta = ii - 1;
fprintf(' %2d %8.4f\n',theta, range(ii));
end
88
© 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(jj) = vxo * time;
y(jj) = vyo * time + 0.5 * g * time^2;
end
plot(x,y,'r','LineWidth',3.0);
hold off
The maximum range of the ball varies as the acceleration due to gravity changes, but the best angle
to throw the ball remains the same:
» ball
Enter g (m/s^2): -9.8
Range versus angle theta:
0 0.0000
1 1.4245
2 2.8472
...
90 0.0000
5.13 A modified version of ball.m that allows the user to specify an initial velocity is shown below.
89
© 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.
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 01/30/14 S. J. Chapman Original code
% 1. 03/27/15 S. J. Chapman Read initial velocity
%
% Define variables:
% conv -- Degrees to radians conv factor
% gravity -- Accel. due to gravity (m/s^2)
% ii, jj -- Loop index
% index -- Location of maximum range in array
% maxangle -- Angle that gives maximum range (deg)
% maxrange -- Maximum range (m)
% range -- Range for a particular angle (m)
% time -- Time (s)
% theta -- Initial angle (deg)
% traj_time -- Total trajectory time (s)
% vo -- Initial velocity (m/s)
% vxo -- X-component of initial velocity (m/s)
% vyo -- Y-component of initial velocity (m/s)
% x -- X-position of ball (m)
% y -- Y-position of ball (m)
% Constants
conv = pi / 180; % Degrees-to-radians conversion factor
g = -9.81; % Accel. due to gravity
90
© 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.
maxrange, maxangle);
The maximum range of the ball varies as the initial velocity changes, but the best angle to throw the
ball remains the same:
» ball
Enter vo (m/s): 10
91
© 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.
Range versus angle theta:
0 0.0000
1 0.3558
2 0.7111
...
90 0.0000
5.14 A modified version of lsqfit.m that uses a while loop to enter data is shown below.
92
© 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 -- Array of x values
% x_bar -- Average x value
% y -- Array of y values
% y_bar -- Average y value
% y_int -- y-axis intercept of the line
% Accumulate statistics
sum_x = 0;
sum_y = 0;
sum_x2 = 0;
sum_xy = 0;
for ii = 1:n_points
sum_x = sum_x + x(ii);
sum_y = sum_y + y(ii);
sum_x2 = sum_x2 + x(ii)^2;
sum_xy = sum_xy + x(ii) * y(ii);
end
% Tell user.
disp('Regression coefficients for the least-squares line:');
fprintf(' Slope (m) = %8.3f\n', slope);
fprintf(' Intercept (b) = %8.3f\n', y_int);
fprintf(' No of points = %8d\n', n_points);
93
© 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.
% Plot a solid red line with no markers
plot([xmin xmax],[ymin ymax],'r-','LineWidth',2);
hold off;
When this program is executed, the results are the same as in Example 4-6:
» lsqfit
This program performs a least-squares fit of an
input data set to a straight line.
Enter [x y] pair: [1.1 1.1]
Enter [x y] pair: [2.2 2.2]
Enter [x y] pair: [3.3 3.3]
Enter [x y] pair: [4.4 4.4]
Enter [x y] pair: [5.5 5.5]
Enter [x y] pair: [6.6 6.6]
Enter [x y] pair: [7.7 7.7]
Enter [x y] pair:
Regression coefficients for the least-squares line:
Slope (m) = 1.000
Intercept (b) = 0.000
No of points = 7
» lsqfit
This program performs a least-squares fit of an
input data set to a straight line.
Enter [x y] pair: [1.1 1.01]
Enter [x y] pair: [2.2 2.30]
Enter [x y] pair: [3.3 3.05]
Enter [x y] pair: [4.4 4.28]
Enter [x y] pair: [5.5 5.75]
Enter [x y] pair: [6.6 6.48]
Enter [x y] pair: [7.7 7.84]
Enter [x y] pair:
Regression coefficients for the least-squares line:
Slope (m) = 1.024
Intercept (b) = -0.120
No of points = 7
5.15 A modified version of lsqfit.m that reads input data from the file input1.dat using the load
function is shown below.
94
© 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.
% and intercept values.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 01/30/14 S. J. Chapman Original code
% 1. 03/27/15 S. J. Chapman Modified to read from input1.dat
%
% Define variables:
% ii -- Loop index
% n_points -- Number in input [x y] points
% slope -- Slope of the line
% sum_x -- Sum of all input x values
% sum_x2 -- Sum of all input x values squared
% sum_xy -- Sum of all input x*y yalues
% sum_y -- Sum of all input y values
% temp -- Variable to read user input
% x -- Array of x values
% x_bar -- Average x value
% y -- Array of y values
% y_bar -- Average y value
% y_int -- y-axis intercept of the line
% Accumulate statistics
sum_x = 0;
sum_y = 0;
sum_x2 = 0;
sum_xy = 0;
for ii = 1:n_points
sum_x = sum_x + x(ii);
sum_y = sum_y + y(ii);
sum_x2 = sum_x2 + x(ii)^2;
sum_xy = sum_xy + x(ii) * y(ii);
end
% Tell user.
disp('Regression coefficients for the least-squares line:');
fprintf(' Slope (m) = %8.3f\n', slope);
95
© 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.
fprintf(' Intercept (b) = %8.3f\n', y_int);
fprintf(' No of points = %8d\n', n_points);
When this program is executed, the results are the same as in Example 5.6. It is necessary to store
each input data set in the file named input1.dat, and then to execute the program using that file.
(This program could be further improved by reading the data from a user-specified file, instead of a
fixed file name.)
5.16 A modified version of lsqfit.m that reads input data from the file input1.dat using the
textread function is shown below.
96
© 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.
%
% Purpose:
% To perform a least-squares fit of an input data set
% to a straight line, and print out the resulting slope
% and intercept values.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 01/30/14 S. J. Chapman Original code
% 1. 03/27/15 S. J. Chapman Modified to read from user file
%
% Define variables:
% filename -- Input file anme
% ii -- Loop index
% n_points -- Number in input [x y] points
% slope -- Slope of the line
% sum_x -- Sum of all input x values
% sum_x2 -- Sum of all input x values squared
% sum_xy -- Sum of all input x*y yalues
% sum_y -- Sum of all input y values
% temp -- Variable to read user input
% x -- Array of x values
% x_bar -- Average x value
% y -- Array of y values
% y_bar -- Average y value
% y_int -- y-axis intercept of the line
% Accumulate statistics
sum_x = 0;
sum_y = 0;
sum_x2 = 0;
sum_xy = 0;
for ii = 1:n_points
sum_x = sum_x + x(ii);
sum_y = sum_y + y(ii);
sum_x2 = sum_x2 + x(ii)^2;
sum_xy = sum_xy + x(ii) * y(ii);
end
97
© 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_bar = sum_x / n_points;
y_bar = sum_y / n_points;
slope = (sum_xy - sum_x * y_bar) / ( sum_x2 - sum_x * x_bar);
y_int = y_bar - slope * x_bar;
% Tell user.
disp('Regression coefficients for the least-squares line:');
fprintf(' Slope (m) = %8.3f\n', slope);
fprintf(' Intercept (b) = %8.3f\n', y_int);
fprintf(' No of points = %8d\n', n_points);
When this program is executed, the results are the same as in Example 5.6. The user specifies which
file to read each time the program is executed.
» lsqfit
This program performs a least-squares fit of an
input data set to a straight line.
Enter file name: input1a.dat
Regression coefficients for the least-squares line:
Slope (m) = 1.000
Intercept (b) = 0.000
No of points = 7
» lsqfit
This program performs a least-squares fit of an
input data set to a straight line.
Enter file name: input1b.dat
Regression coefficients for the least-squares line:
Slope (m) = 1.024
Intercept (b) = -0.120
No of points = 7
98
© 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.
5.17 The MATLAB function to calculate the factorial function is factorial(n). The result of this
function are:
>> factorial(5)
ans =
120
>> factorial(10)
ans =
3628800
>> factorial(15)
ans =
1.3077e+012
5.18 A program to smooth a noisy data set with a running average filter is shown below. Note that this
program prompts the user for the name of the input data file and the number of points to use in
smoothing.
The number of points used in smoothing should be an odd number, so that there are an equal number
of points on either side of the one being averaged. To accommodate this, the program calculates the
number of points on either side of the center using the equation n_per_side = (n_ave-1) /
2. If the user entered an even number of points, this result will contain a fraction. We take care of
this possibility by throwing away fractional part using the floor function.
Next the program has to worry about the ends of the data sets, where there are less than
n_per_side points available for averaging. It does this for each point by calculating the number
of points available on each side of the point being averaged, and using the smaller of those two
numbers if it is less than n_per_side.
99
© 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.
% Get the number of samples on either side of the sample
% being averaged, dropping any fractional part.
n_per_side = (n_ave-1) / 2;
n_per_side = floor(n_per_side);
end
>> running_ave
This program performs a running average filter on an
input data set.
Enter the filename containing the data: input3.dat
Enter the number of samples to average: 7
100
© 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.
5.19 A program to smooth a noisy data set with a median filter is shown below. Note that this program
prompts the user for the name of the input data file and the number of points to use in smoothing.
end
>> median
This program performs a median filter on an input data set.
Enter the filename containing the data: input3.dat
Enter the number of samples to average: 7
102
© 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 median filter is better than the running average filter in situations where there are really wild
points (line the ones at 28 and 71 in the data set input3.dat). These wild points perturb the
running average filter more than the median filter.
5.20 A program to calculate and plot 3, 5, and 10 terms of Fourier series approximation to a square wave
is shown below. Note that the more terms we use, the better the approximation becomes.
104
© 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:
5.21 A version of program doy that checks for the validity of the input days and months is shown below.
105
© 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.
month = input('Enter current month (1-12): ');
day = input('Enter current day(1-31): ');
year = input('Enter current year(yyyy): ');
else
else
end
106
© 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.
% Tell user
fprintf('The date %2d/%2d/%4d is day of year %d.\n', ...
month, day, year, day_of_year);
end
end
5.22 A program to evaluate the function ln 1 repeatedly for legal inputs is shown below.
1− x
5.23 A program to calculate the nth Fibonacci number using a while loop is shown below. Note that
this program tests to make sure that the input value is greater than 2, and that it is an integer.
% Get n
n = input('Enter the Fibonacci number n to evaluate (n>2): ');
elseif round(n) ~= n
else
% Calculate fn
fn = zeros(1,n);
fn(1) = 1;
fn(2) = 2;
ii = 3;
while ii <= n;
fn(ii) = fn(ii-1) + fn(ii-2);
ii = ii + 1;
end
% Display result
disp(['The ' int2str(n) 'th Fibonacci number = ' int2str(fn(n))]);
end
When this program is executed, the results are as shown below. Note that the error checks are
working properly, and the main calculations are also correct.
>> fibonacci
Enter the Fibonacci number n to evaluate (n>2): -1
Error--n must greater than two!
>> fibonacci
Enter the Fibonacci number n to evaluate (n>2): 3.4
Error--n must be an integer!
>> fibonacci
Enter the Fibonacci number n to evaluate (n>2): 3
The 3th Fibonacci number = 3
>> fibonacci
Enter the Fibonacci number n to evaluate (n>2): 4
The 4th Fibonacci number = 5
>> fibonacci
Enter the Fibonacci number n to evaluate (n>2): 9
The 9th Fibonacci number = 55
5.24 A program to calculate and plot the current flowing through a diode as a function of frequency is:
108
© 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.
% Purpose:
% This program calculates and plots the current flowing
% through a diode as a function of the voltage across it.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/01/15 S. J. Chapman Original code
%
% Define variables:
% i0 -- Leakage current (A)
% id -- Diode current (A)
% k -- Boltzmann's constant (joule/K)
% q -- Charge on an electron (coul)
% temp_f -- Temperature (deg F)
% temp_k -- Temperature (K)
% vd -- Diode voltage (V)
% Initial values
i0 = 2.0e-6; % amps
k = 1.38e-23; % joule/K
q = 1.602e-19; % Coulombs
vd = -1.0:0.01:0.6; % Volts
temp_f = [75 100 125]; % def F
for ii = 1:length(temp_f)
% Calculate currents
id = i0 .* ( exp((q*vd)/(k*temp_k)) - 1 );
elseif ii == 2
plot(vd,id,'k--','LineWidth',2);
elseif ii == 3
plot(vd,id,'r:','LineWidth',2);
hold off;
end
end
legend('75° F', '100° F', '125° F')
grid on;
title('\bfPlot of diode voltage vs diode current');
xlabel('\bf\itv_{D}');
ylabel('\bf\iti_{D}');
109
© 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:
5.25 A program to find the attachment point that minimizes the tension on a cable is shown below:
% Initial values
lc = 2;
lp = 2;
110
© 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.
weight = 100;
clear dist tension
% Calculate tension
dist(jj) = ii;
tension(jj) = weight * lc * lp ...
/ ( dist(jj) * sqrt(lp^2 - dist(jj)^2) );
saved_tension = tension(jj);
saved_dist = dist(jj);
end
end
>> cable
Minimum tension at 1.4
Minimum tension = 200.04
111
© 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.
5.26 A program to find the range of attachment points within 10% of the minimum tension is shown
below. Note that we have calculated the data at a smaller step size (0.01 m) to improve the accuracy
of the limits.
112
© 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.
% Initial values
lc = 2;
lp = 2;
weight = 100;
clear dist tension
% Calculate tension
dist(jj) = ii;
tension(jj) = weight * lc * lp ...
/ ( dist(jj) * sqrt(lp^2 - dist(jj)^2) );
saved_tension = tension(jj);
saved_dist = dist(jj);
saved_index = jj;
end
end
for ii = saved_index:-1:1
if tension(ii) <= tension_limit
min_dist = dist(ii);
113
© 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.
else
break;
end
end
>> cable
Minimum tension at 1.41
Minimum tension = 200.0035
Tension is within 10% of min between 1.09 and 1.68
114
© 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.
5.27 A program to calculate the area of a parallelogram using the cross product is shown below. Note
that the cross product works on three-dimensional vectors, so the input must be in the form of the
coefficients of a vector x î + y ĵ + z k̂ , with the three coefficients given as a MATLAB vector:
% Calculate area
area = abs(cross(a,b));
% Tell user
disp(['The area is ' num2str(area)]);
>> parallelogram
This program calculates the area of a parallelogram defined.
by vectors representing two adjacent sides.
Enter vector representing side A (three dimensions): [10 0 0]
Enter vector representing side B (three dimensions): [5 8.66 0]
The area is 0 0 86.6
given by the equation P = 2W + 2H . If the total perimeter is limited to 10, then the height of the
rectangle is related to the width by
10−2W
H=
2
where 0 W 5 (otherwise the width would be negative). Therefore, the program must calculate
the area of the rectangle as the height is varied from 0 to 5.
115
© 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.
% Script file: area_of_rectangle.m
116
© 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.
%
% Purpose:
% To calculate the larges area possible for a rectangle
% of perimeter 10.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/02/15 S. J. Chapman Original code
%
% Define variables:
% area -- Area of rectange
% h -- Height of rectangle
% w -- Width of rectangle
% saved_area -- Saved area of rectange
% saved_h -- Saved height of rectangle
% saved_w -- Saved width of rectangle
% Calculate heights
h = (10 - 2.*w) ./ 2;
% Tell user
disp(['The maximum area is ' num2str(saved_area) ' at width = ' ...
num2str(saved_w) ' and height = ' num2str(saved_h)]);
117
© 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.
When this program is executed, the results are as shown below.
>> area_of_rectangle
The maximum area is 6.25 at width = 2.5 and height = 2.5
5.29 A program to calculate the amount of bacteria found in two different culture media over time is
shown below. Note that both linear and semilogy plots are created.
% Print heading.
disp('The rates of colony growth are: ');
disp(' Time Colony 1 Colony 2');
disp(' ==== ======== ========');
% Set time
time(ii) = 3 *(ii-1);
% Tell user
fprintf(' %6.1f%12.1f%12.1f\n',time(ii), ...
n_bacteria_1(ii), n_bacteria_2(ii));
end
figure(2);
semilogy(time,n_bacteria_1,'b-','LineWidth',2);
hold on;
semilogy(time,n_bacteria_2,'k--','LineWidth',2);
title('\bfPlot of colony size vs time');
xlabel('\bfTime (hours)');
ylabel('\bfColony size');
legend('Medium 1','Medium 2');
grid on;
» bacteria
The rates of colony growth are:
Time Colony 1 Colony 2
==== ======== ========
119
© 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.
0.0 1.0 1.0
3.0 8.0 4.0
6.0 64.0 16.0
9.0 512.0 64.0
12.0 4096.0 256.0
15.0 32768.0 1024.0
18.0 262144.0 4096.0
21.0 2097152.0 16384.0
24.0 16777216.0 65536.0
119
© 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.
5.30 A program to calculate and plot the dBW values corresponding to a given input power is shown
below:
% Calculate dBm
dBW = 10 * log10( pin / 1.0 );
120
© 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.
ylabel('\bfdBW');
grid on;
5.31 A program to calculate the geometric mean of a set of positive numbers is shown below. This
program uses a while loop to get the input values.
% Tell user
fprintf('The geometric mean is %.4f\n',g);
» geometric_mean
Enter first number: 10
Enter next number: 5
Enter next number: 2
Enter next number: 5
Enter next number: -1
The geometric mean is 4.7287
5.32 A program to calculate the rms average of a set of positive numbers is shown below. This program
uses a for loop to get the input values.
% Initialize sum
sum2 = 0;
122
© 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.
sum2 = sum2 + x^2;
end
% Tell user
fprintf('The rms average is %.4f\n',rms);
» rms_average
Enter number of values: 4
Enter number: 10
Enter number: 5
Enter number: 2
Enter number: 5
The rms average is 6.2048
5.33 A program to calculate the harmonic mean of a set of positive numbers is shown below. This
program uses a for loop to get the input values. Note that while loops could also have been used.
% Initialize sum
sumr = 0;
123
© 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.
% Tell user
fprintf('The harmonic mean is %.4f\n',hmean);
» harmonic_mean
Enter number of values: 4
Enter number: 10
Enter number: 5
Enter number: 2
Enter number: 5
The harmonic mean is 4.0000
5.34 A program to calculate the arithmetic mean, geometric mean, harmonic mean, and rms average of a
set of positive numbers is shown below.
% Initialize sums
prod = 1;
sum = 0;
sumr = 0;
sum2 = 0;
124
© 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.
sum2 = sum2 + x^2;
sumr = sumr + 1/x;
end
% Tell user
fprintf('Arithmetic mean = %.4f\n',ave);
fprintf('Geometric mean = %.4f\n',g);
fprintf('Harmonic mean = %.4f\n',hmean);
fprintf('Rms average = %.4f\n',rms);
» all_means
Enter number of values: 7
Enter number: 4
Enter number: 4
Enter number: 4
Enter number: 4
Enter number: 4
Enter number: 4
Enter number: 4
Arithmetic mean = 4.0000
Geometric mean = 4.0000
Harmonic mean = 4.0000
Rms average = 4.0000
» all_means
Enter number of values: 7
Enter number: 4
Enter number: 3
Enter number: 4
Enter number: 5
Enter number: 4
Enter number: 3
Enter number: 5
Arithmetic mean = 4.0000
Geometric mean = 3.9269
Harmonic mean = 3.8532
Rms average = 4.0708
» all_means
Enter number of values: 7
Enter number: 4
Enter number: 1
Enter number: 4
Enter number: 7
Enter number: 4
Enter number: 1
Enter number: 7
125
© 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.
Arithmetic mean = 4.0000
Geometric mean = 3.1585
Harmonic mean = 2.3059
Rms average = 4.5981
» all_means
Enter number of values: 7
Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
Enter number: 6
Enter number: 7
Arithmetic mean = 4.0000
Geometric mean = 3.3800
Harmonic mean = 2.6997
Rms average = 4.4721
5.35 A program to calculate the mean time between failures of a system consisting of a series of
subsystems with known MTBFs is shown below.
% Initialize sum
sumr = 0;
126
© 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.
% Tell user
fprintf('The overall system MTBF is %.4f hours.\n',mtbf);
» mtbf
Enter number of subsystems: 4
Enter MTBF of Subsystem 1: 2000
Enter MTBF of Subsystem 2: 800
Enter MTBF of Subsystem 3: 3000
Enter MTBF of Subsystem 4: 5000
The overall system MTBF is 437.9562 hours.
127
© 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.
128
© 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.