You are on page 1of 52

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/

5. Loops and Vectorization


5.1 The MATLAB statements to evaluate the expression with loops are

% Script file: eval_loop.m


%
% Purpose:
% This program evaluates the specified function over
% the range -9 to 9 in steps of 0.5, using loops.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/25/15 S. J. Chapman Original code
%
% Define variables:
% ii -- Loop index
% t -- Independent variable
% y -- Dependent variable

% Evaluate with loops


%
t = -9:0.5:9;
y = zeros(size(t));
for ii = 1:length(t)
if t(ii) >= 0
y(ii) = -3 * t(ii)^2 + 5;
else
y(ii) = 3 * t(ii)^2 + 5;
end
end
%
79
© 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.
% Diplay result
%
plot(t,y,'LineWidth',2);
xlabel('\bf\itt');
ylabel('\bf\ity');
grid on;

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

% Script file: eval_vector.m


%
% Purpose:
% This program evaluates the specified function over
% the range -9 to 9 in steps of 0.5, using vectors.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/25/15 S. J. Chapman Original code
%
% Define variables:
% ii -- Loop index
% t -- Independent variable
% test -- Logical array for masking
% y -- Dependent variable

% Evaluate with vectors


%
t = -9:0.5:9;
test = t > 0;
y(test) = -3 * t(test).^2 + 5;
y(~test) = 3 * t(~test).^2 + 5;
%
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.
% Diplay result
%
plot(t,y,'LineWidth',2);
xlabel('\bf\itt');
ylabel('\bf\ity');
grid on;

The resulting plot is identical, as shown below:

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');

% Create and print squares


for ii = 0:2:50
square = ii^2;
fprintf(' %3d %6d\n',ii,square);
end

When these statements are executed, the results are:

» 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

5.4 An M-file to evaluate the equation y ( x ) = x 2 − 3 x + 2 is shown below.

% Script file: calc_function.m


%
% Purpose:
% This program calculates the equation y(x) = x^2 - 3*x + 2
% for values of x between -1 and 3.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/25/15 S. J. Chapman Original code
%
% Define variables:
% ii -- Loop index
% square -- Squares

% Calculate in a for loop


for ii = 1:41
x(ii) = (ii-11)/10;
y(ii) = x(ii)^2 - 3*x(ii) + 2;
end

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

5.5 An M-file to calculate N! is shown below.

% Script file: factorial.m


%
% Purpose:
% This program evaluates N!.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/25/15 S. J. Chapman Original code
%
% Define variables:
% fact -- n!
% n -- Input value

% Get n
n = input('Enter n: ');

% Check to see that n is a positive integer


if n < 0

disp('Error--n must be non-negative!');

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

When this program is executed, the results are:

» 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.9 (a) arr1 = 5 −6 7 −8  ; (b) arr1 =  0 36 49 64  .


   
9 −10 11 −12 81 100 121 144
84
© 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.10 A logical array can be made to behave as a mask for vector operations by using it as a subscript for
the vector operands. Any true value in the array causes that element to be selected.

5.11 A modified version of ball.m with vectorized inner loops is shown below.

% 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 Vectorized inner loops
%
% 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
vo = 20; % Initial velocity

%Create an array to hold ranges


range = zeros(1,91);

% Calculate maximum ranges (vectorized)


theta = 0:90;
vxo = vo * cos(theta*conv);
vyo = vo * sin(theta*conv);
max_time = -2 * vyo / g;
range = vxo .* max_time;

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

% Calculate the maximum range and angle


[maxrange index] = max(range);
maxangle = index - 1;
fprintf ('\nMax range is %8.4f at %2d degrees.\n',...
maxrange, maxangle);

% Now plot the trajectories


for ii = 5:10:85

% Get velocities and max time for this angle


theta = ii;
vxo = vo * cos(theta*conv);
vyo = vo * sin(theta*conv);
traj_time = -2 * vyo / g;

% Calculate the (x,y) positions (vectorized)


time = 0:0.05:1 * max_time;
x = vxo * time;
y = vyo * time + 0.5 * g * time.^2;
plot(x,y,'b');
if ii == 5
hold on;
end
end

% Add titles and axis lables


title ('\bfTrajectory of Ball vs Initial Angle \theta');
xlabel ('\bf\itx \rm\bf(meters)');
ylabel ('\bf\ity \rm\bf(meters)');
axis ([0 45 0 25]);
grid on;

% Now plot the max range trajectory


vxo = vo * cos(maxangle*conv);
vyo = vo * sin(maxangle*conv);
traj_time = -2 * vyo / g;

% Calculate the (x,y) positions (vectorized)


time = 0:0.05:1 * max_time;
x = vxo * time;
y = vyo * time + 0.5 * g * time.^2;
plot(x,y,'r','LineWidth',3.0);
hold off

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

% Get acceleration due to gravity


g = input('Enter g (m/s^2): ');

% Create an array to hold ranges


range = zeros(1,91);

% Calculate maximum ranges


for ii = 1:91
theta = ii - 1;
vxo = vo * cos(theta*conv);
vyo = vo * sin(theta*conv);
max_time = -2 * vyo / g;
range(ii) = vxo * max_time;
end

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

% Calculate the maximum range and angle


[maxrange index] = max(range);
maxangle = index - 1;
fprintf ('\nMax range is %8.4f at %2d degrees.\n',...
maxrange, maxangle);

% Now plot the trajectories


for ii = 5:10:85

% Get velocities and max time for this angle


theta = ii;
vxo = vo * cos(theta*conv);
vyo = vo * sin(theta*conv);
max_time = -2 * vyo / g;

% Calculate the (x,y) positions


x = zeros(1,21);
y = zeros(1,21);
for jj = 1:21
time = (jj-1) * max_time/20;
x(jj) = vxo * time;
y(jj) = vyo * time + 0.5 * g * time^2;
end
plot(x,y,'b');
if ii == 5
hold on;
end
end

% Add titles and axis lables


title ('\bfTrajectory of Ball vs Initial Angle \theta');
xlabel ('\bf\itx \rm\bf(meters)');
ylabel ('\bf\ity \rm\bf(meters)');
axis ([0 45 0 25]);
grid on;

% Now plot the max range trajectory


vxo = vo * cos(maxangle*conv);
vyo = vo * sin(maxangle*conv);
max_time = -2 * vyo / g;

% Calculate the (x,y) positions


x = zeros(1,21);
y = zeros(1,21);
for jj = 1:21
time = (jj-1) * max_time/20;

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

Max range is 40.8163 at 45 degrees.


» ball
Enter g (m/s^2): -9.7
Range versus angle theta:
0 0.0000
1 1.4392
2 2.8766
...
90 0.0000

Max range is 41.2371 at 45 degrees.


»
» ball
Enter g (m/s^2): -9.6
Range versus angle theta:
0 0.0000
1 1.4541
2 2.9065
...
90 0.0000

Max range is 41.6667 at 45 degrees.

5.13 A modified version of ball.m that allows the user to specify an initial velocity is shown below.

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

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

% Get initial velocity


vo = input('Enter vo (m/s): ');

% Create an array to hold ranges


range = zeros(1,91);

% Calculate maximum ranges


for ii = 1:91
theta = ii - 1;
vxo = vo * cos(theta*conv);
vyo = vo * sin(theta*conv);
max_time = -2 * vyo / g;
range(ii) = vxo * max_time;
end

% 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

% Calculate the maximum range and angle


[maxrange index] = max(range);
maxangle = index - 1;
fprintf ('\nMax range is %8.4f at %2d degrees.\n',...

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);

% Now plot the trajectories


for ii = 5:10:85

% Get velocities and max time for this angle


theta = ii;
vxo = vo * cos(theta*conv);
vyo = vo * sin(theta*conv);
max_time = -2 * vyo / g;

% Calculate the (x,y) positions


x = zeros(1,21);
y = zeros(1,21);
for jj = 1:21
time = (jj-1) * max_time/20;
x(jj) = vxo * time;
y(jj) = vyo * time + 0.5 * g * time^2;
end
plot(x,y,'b');
if ii == 5
hold on;
end
end

% Add titles and axis lables


title ('\bfTrajectory of Ball vs Initial Angle \theta');
xlabel ('\bf\itx \rm\bf(meters)');
ylabel ('\bf\ity \rm\bf(meters)');
axis ([0 45 0 25]);
grid on;

% Now plot the max range trajectory


vxo = vo * cos(maxangle*conv);
vyo = vo * sin(maxangle*conv);
max_time = -2 * vyo / g;

% Calculate the (x,y) positions


x = zeros(1,21);
y = zeros(1,21);
for jj = 1:21
time = (jj-1) * max_time/20;
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 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

Max range is 10.1937 at 45 degrees.


» ball
Enter vo (m/s): 20
Range versus angle theta:
0 0.0000
1 1.4230
2 2.8443
...
90 0.0000

Max range is 40.7747 at 45 degrees.


» ball
Enter vo (m/s): 30
Range versus angle theta:
0 0.0000
1 3.2018
2 6.3997
...
90 0.0000

Max range is 91.7431 at 45 degrees.

5.14 A modified version of lsqfit.m that uses a while loop to enter data is shown below.

% Script file: lsqfit.m


%
% 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 use a while loop
%
% 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

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

disp('This program performs a least-squares fit of an ');


disp('input data set to a straight line.');

% Read the input data


n_points = 0;
temp = input('Enter [x y] pair: ');
while ~isempty(temp)
n_points = n_points + 1;
x(n_points) = temp(1);
y(n_points) = temp(2);
temp = input('Enter [x y] pair: ');
end

% 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

% Now calculate the slope and intercept.


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);

% Plot the data points as blue circles with no


% connecting lines.
plot(x,y,'bo');
hold on;

% Create the fitted line


xmin = min(x);
xmax = max(x);
ymin = slope * xmin + y_int;
ymax = slope * xmax + y_int;

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;

% Add a title and legend


title ('\bfLeast-Squares Fit');
xlabel('\bf\itx');
ylabel('\bf\ity');
legend('Input data','Fitted line');
grid on

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.

% Script file: lsqfit.m


%
% Purpose:
% To perform a least-squares fit of an input data set
% to a straight line, and print out the resulting slope

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

disp('This program performs a least-squares fit of an ');


disp('input data set to a straight line.');

% Read the input data


load input1.dat
x = input1(:,1); y =
input1(:,2); n_points
= length(x);

% 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

% Now calculate the slope and intercept.


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);

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);

% Plot the data points as blue circles with no


% connecting lines.
plot(x,y,'bo');
hold on;

% Create the fitted line


xmin = min(x);
xmax = max(x);
ymin = slope * xmin + y_int;
ymax = slope * xmax + y_int;

% Plot a solid red line with no markers


plot([xmin xmax],[ymin ymax],'r-','LineWidth',2);
hold off;

% Add a title and legend


title ('\bfLeast-Squares Fit');
xlabel('\bf\itx');
ylabel('\bf\ity');
legend('Input data','Fitted line');
grid on

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

» !copy input1a.dat input1.dat


1 file(s) copied.
» lsqfit
This program performs a least-squares fit of an
input data set to a straight line.
Regression coefficients for the least-squares line:
Slope (m) = 1.000
Intercept (b) = 0.000
No of points = 7
» !copy input1b.dat input1.dat
1 file(s) copied.
» lsqfit
This program performs a least-squares fit of an
input data set to a straight line.
Regression coefficients for the least-squares line:
Slope (m) = 1.024
Intercept (b) = -0.120
No of points = 7

5.16 A modified version of lsqfit.m that reads input data from the file input1.dat using the
textread function is shown below.

% Script file: lsqfit.m

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

disp('This program performs a least-squares fit of an ');


disp('input data set to a straight line.');

% Get the file name to read


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

% Read the input data


in_data = textread(filename);
x = in_data(:,1); y =
in_data(:,2);
n_points = length(x);

% 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

% Now calculate the slope and intercept.

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);

% Plot the data points as blue circles with no


% connecting lines.
plot(x,y,'bo');
hold on;

% Create the fitted line


xmin = min(x);
xmax = max(x);
ymin = slope * xmin + y_int;
ymax = slope * xmax + y_int;

% Plot a solid red line with no markers


plot([xmin xmax],[ymin ymax],'r-','LineWidth',2);
hold off;

% Add a title and legend


title ('\bfLeast-Squares Fit');
xlabel('\bf\itx');
ylabel('\bf\ity');
legend('Input data','Fitted line');
grid on

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.

% Script file: running_ave.m


%
% Purpose:
% To perform a running average filter on an input data set.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/30/15 S. J. Chapman Original code
%
% Define variables:
% ii -- Loop index
% filename -- Input data file
% n_ave -- Number of points to average
% n_per_side -- Number of points to average per side
% n_points -- Number of points in data set
% slope -- Slope of the line
% x -- Array of input values
% y -- Array of filtered values

disp('This program performs a running average filter on an ');


disp('input data set.');
filename = input('Enter the filename containing the data: ','s');
n_ave = input('Enter the number of samples to average: ');

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);

% Read the input data


x = textread(filename,'%f');
n_points = length(x);

% Now perform the running average


for ii = 1:n_points

% Check to see how many points we can use on either side


% of the point being averaged.
n_low = min([ (ii-1) n_per_side]);
n_high = min([ (n_points-ii) n_per_side]);
n_used = min([ n_low n_high]);

% Now calculate running average


y(ii) = sum(x(ii-n_used:ii+n_used)) / (2*n_used+1);

end

% Plot the data points as blue circles with no


% connecting lines.
plot(x,'bo');
hold on;

% Plot the fit as a solid red line with no markers


plot(y,'r-','LineWidth',2);
hold off;

% Add a title and legend


title ('\bfRunning-Average Filter');
xlabel('\bf\itx');
ylabel('\bf\ity');
legend('Input data','Fitted line');
grid on

When this program is executed, the results are:

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

% Script file: median_filter.m


%
% Purpose:
% To perform a median filter on an input data set.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/30/15 S. J. Chapman Original code
%
% Define variables:
% ii -- Loop index
% filename -- Input data file
% n_ave -- Number of points to average
% n_per_side -- Number of points to average per side
% n_points -- Number of points in data set
% slope -- Slope of the line
% x -- Array of input values
% y -- Array of filtered values

disp('This program performs a median filter on an input data set.');


filename = input('Enter the filename containing the data: ','s');
n_ave = input('Enter the number of samples to average: ');

% Get the number of samples on either side of the sample


% being averaged, dropping any fractional part.
101
© 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.
n_per_side = (n_ave-1) / 2;
n_per_side = floor(n_per_side);

% Read the input data


x = textread(filename,'%f');
n_points = length(x);

% Now perform the running average


for ii = 1:n_points

% Check to see how many points we can use on either side


% of the point being averaged.
n_low = min([ (ii-1) n_per_side]);
n_high = min([ (n_points-ii) n_per_side]);
n_used = min([ n_low n_high]);

% Now calculate running average


y(ii) = median(x(ii-n_used:ii+n_used));

end

% Plot the data points as blue circles with no


% connecting lines.
plot(x,'bo');
hold on;

% Plot the fit as a solid red line with no markers


plot(y,'r-','LineWidth',2);
hold off;

% Add a title and legend


title ('\bfMedian Filter');
xlabel('\bf\itx');
ylabel('\bf\ity');
legend('Input data','Fitted line');
grid on

When this program is executed, the results are:

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

% Script file: fourier_series.m


%
% Purpose:
% To plot 3, 5, and 10 terms of a Fourier series approximation
% to a square wave.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/30/15 S. J. Chapman Original code
%
% Define variables:
% x -- Array of x values
% y3 -- Three-term approimation
% y5 -- Five-term approimation
% y10 -- Ten-term approimation

% Get the input data points


x = -2:0.001:2;

% Calculate the Fourier series approximation to 3 terms


103
© 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.
y3 = zeros(size(x));
for n = 1:2:5
y3 = y3 + (1/n) .* sin(n*pi*x);
end

% Calculate the Fourier series approximation to 5 terms


y5 = zeros(size(x));
for n = 1:2:9
y5 = y5 + (1/n) .* sin(n*pi*x);
end

% Calculate the Fourier series approximation to 10 terms


y10 = zeros(size(x));
for n = 1:2:19
y10 = y10 + (1/n) .* sin(n*pi*x);
end

% Plot the approximations


plot(x,y3,'r-','LineWidth',2);
hold on;
plot(x,y5,'b--','LineWidth',2);
plot(x,y10,'k-.','LineWidth',2);
hold off;

% Add a title and legend


title ('\bfFourier Series Approximations');
xlabel('\bf\itx');
ylabel('\bf\itf(x)');
legend('3 terms','5 terms','10 terms');
grid on

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.

% Script file: doy.m


%
% Purpose:
% This program calculates the day of year corresponding
% to a specified date. It illustrates the use switch and
% for constructs.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 01/27/14 S. J. Chapman Original code
% 1. 03/30/15 S. J. Chapman Modified to check for validity
%
% Define variables:
% day -- Day (dd)
% day_of_year -- Day of year
% ii -- Loop index
% leap_day -- Extra day for leap year
% max_day -- Last day in a month
% month -- Month (mm)
% year -- Year (yyyy)

% Get day, month, and year to convert


disp('This program calculates the day of year given the ');
disp('current date.');

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): ');

% Check for leap year, and add extra day if necessary


if mod(year,400) == 0
leap_day = 1; % Years divisible by 400 are leap years
elseif mod(year,100) == 0
leap_day = 0; % Other centuries are not leap years
elseif mod(year,4) == 0
leap_day = 1; % Otherwise every 4th year is a leap year
else
leap_day = 0; % Other years are not leap years
end

% Check to see if month is valid valid


if month < 1 | month > 12
disp('Error--invalid month');

else

% Check to see if day is valid


switch (month)
case {1,3,5,7,8,10,12},
max_day = 31;
case {4,6,9,11},
max_day = 30;
case 2,
max_day = 28 + leap_day;
end

if day < 1 | day > max_day


disp('Error--invalid day');

else

% Everthing is ok. Calculate the day of year


% by adding current day to the days in
% previous months.
day_of_year = day;
for ii = 1:month-1

% Add days in months from January to last month


switch (ii)
case {1,3,5,7,8,10,12},
day_of_year = day_of_year + 31;
case {4,6,9,11},
day_of_year = day_of_year + 30;
case 2,
day_of_year = day_of_year + 28 + leap_day;
end

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

% Script file: eval_fn.m


%
% Purpose:
% This program evaluates a function, first checking
% to ensure that the input argument is legal. Evaluate
% this function repeatedly until an illegal value is
% entered.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/30/15 S. J. Chapman Original code
%
% Define variables:
% x -- Independent variable
% fun -- Resulting function

% Prompt the user for the value x


x = input ('Enter x: ');

% Calculate the function


while x < 1
fun = log( 1 / (1-x) );
disp(['log( 1 / (1-x) ) = ' num2str(fun)]);
x = input ('Enter x: ');
end
disp('Ending...');

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.

% Script file: fibonacci.m


%
% Purpose:
% This program evaluates the nth Fibonacci number.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 03/30/15 S. J. Chapman Original code
%
% Define variables:
% fn -- Fibonacci number
107
© 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.
% n -- The item in the sequence to calculate

% Get n
n = input('Enter the Fibonacci number n to evaluate (n>2): ');

% Check to see that n is an integer greater than two


if n <= 2

disp('Error--n must greater than two!');

elseif round(n) ~= n

disp('Error--n must be an integer!');

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:

% Script file: diode.m


%

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)

% Convert temperature to kelvins.


temp_k = (5/9) * (temp_f(ii) - 32) + 273.15;

% Calculate currents
id = i0 .* ( exp((q*vd)/(k*temp_k)) - 1 );

% Plot line in various colors


if ii == 1
plot(vd,id,'b-','LineWidth',2);
hold on;

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:

% Script file: cable.m


%
% Purpose:
% To calculate the connection point that results in
% minimum tension on a cable.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/01/15 S. J. Chapman Original code
%
% Define variables:
% dist -- Distance to attachment (m)
% lc -- Cable length (m)
% ii -- index variable
% lp -- Pole length (m)
% saved_dist -- Save attachment distance
% saved_tension -- Saved tension
% tension -- Tension on cable
% weight -- Weight of object (kg)

% 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 at 0.3 m


dist(1) = 0.3;
tension(1) = weight * lc * lp ...
/ ( dist(1) * sqrt(lp^2 - dist(1)^2) );

% Save these initial values for comparision


saved_dist = dist;
saved_tension = tension;

% Calculate for other values between 0.4 and 1.8 m


jj = 1;
for ii = 0.4:0.1:1.8

% Update array index


jj = jj + 1;

% Calculate tension
dist(jj) = ii;
tension(jj) = weight * lc * lp ...
/ ( dist(jj) * sqrt(lp^2 - dist(jj)^2) );

% Find minimum tension point


if tension(jj) < saved_tension

saved_tension = tension(jj);
saved_dist = dist(jj);

end
end

% Display minimum tension point


disp(['Minimum tension at ' num2str(saved_dist)]);
disp(['Minimum tension = ' num2str(saved_tension)]);

% Plot tension vs distance


figure(1);
plot(dist,tension,'b-','LineWidth',2);
grid on;
title('\bfPlot of tension vs attachment distance');
xlabel('\bfDistance');
ylabel('\bfTension');

When this program is executed, the results are:

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

% Script file: cable.m


%
% Purpose:
% To calculate the range of connection points that result
% in cable tension within 10% of the minimum value.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/01/15 S. J. Chapman Original code
%
% Define variables:
% dist -- Distance to attachment (m)
% lc -- Cable length (m)
% ii -- index variable
% jj -- index variable
% lp -- Pole length (m)
% max_dist -- Max distance within 10% of min tension
% min_dist -- Min distance within 10% of min tension
% saved_dist -- Save attachment distance
% saved_index -- Index of minimum tension value
% saved_tension -- Saved tension
% tension -- Tension on cable
% weight -- Weight of object (kg)

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 at 0.3 m


dist(1) = 0.3;
tension(1) = weight * lc * lp ...
/ ( dist(1) * sqrt(lp^2 - dist(1)^2) );

% Save these initial values for comparision


saved_dist = dist;
saved_tension = tension;

% Calculate for other values between 0.31 and 1.8 m


jj = 1;
for ii = 0.31:0.01:1.8

% Update array index


jj = jj + 1;

% Calculate tension
dist(jj) = ii;
tension(jj) = weight * lc * lp ...
/ ( dist(jj) * sqrt(lp^2 - dist(jj)^2) );

% Find minimum tension point


if tension(jj) < saved_tension

saved_tension = tension(jj);
saved_dist = dist(jj);
saved_index = jj;

end
end

% Now calculate the value that is 10% greater than


% the minimum.
tension_limit = 1.1 * saved_tension;

% Now find the values within that range.


for ii = saved_index:length(dist)
if tension(ii) <= tension_limit
max_dist = dist(ii);
else
break;
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

% Display minimum tension point


disp(['Minimum tension at ' num2str(saved_dist)]);
disp(['Minimum tension = ' num2str(saved_tension)]);

% Display the limits where tension is withn 10% of min


disp(['Tension is within 10% of min between ' num2str(min_dist) ...
' and ' num2str(max_dist)]);

% Plot tension vs distance


figure(1);
plot(dist,tension,'b-','LineWidth',2);
grid on;
title('\bfPlot of tension vs attachment distance');
xlabel('\bfDistance');
ylabel('\bfTension');

When this program is executed, the results are:

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

% Script file: parallelogram.m


%
% Purpose:
% To calculate the area of a parallelogram defined by two
% vectors representing adjacent sides.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/01/15 S. J. Chapman Original code
%
% Define variables:
% a -- First vector
% area -- Area of parallelogram
% b -- Second vector

disp('This program calculates the area of a parallelogram defined.');


disp('by vectors representing two adjacent sides.');
a = input('Enter vector representing side A (three dimensions): ');
b = input('Enter vector representing side B (three dimensions): ');

% Calculate area
area = abs(cross(a,b));

% Tell user
disp(['The area is ' num2str(area)]);

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

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

The area of the parallelogram is 86.6.


5.28 The area of a rectangle is given by the equation A = W  H and the perimeter of the rectangle is

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

% Get an array of widths


w = 0:0.1:5;

% Calculate heights
h = (10 - 2.*w) ./ 2;

% Calculate the aera of the rectanges


area = w .* h;

% Find the maximum area


saved_area = 0;
saved_w = 0;
saved_h = 0;
for ii = 1:length(w)
if area(ii) > saved_area
saved_area = area(ii);
saved_w = w(ii);
saved_h = h(ii);
end
end

% Tell user
disp(['The maximum area is ' num2str(saved_area) ' at width = ' ...
num2str(saved_w) ' and height = ' num2str(saved_h)]);

% Plot area vs width


figure(1);
plot(w,area,'b-','LineWidth',2);
grid on;
title('\bfPlot of area vs width');
xlabel('\bfWidth');
ylabel('\bfArea');

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

The area of the rectangle vs width is shown below:

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.

% Script file: bacteria.m


%
% Purpose:
% Program to calculate rate of bacterial growth in
% different culture media.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/02/15 S. J. Chapman Original code
%
% Define variables:
% double_time_1 -- Doubling time of medium 1 (hrs)
% double_time_2 -- Doubling time of medium 2 (hrs)
% ii -- index variable
% n_bact_1 -- Number of bacterial in medium 1
% n_bact_2 -- Number of bacterial in medium 2
% time -- Time (hrs)
118
© 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
double_time_1 = 1.0;
double_time_2 = 1.5;

% Print heading.
disp('The rates of colony growth are: ');
disp(' Time Colony 1 Colony 2');
disp(' ==== ======== ========');

% Calculate the sizes of each colony


for ii = 1:9

% Set time
time(ii) = 3 *(ii-1);

% Calculate colony size


n_bacteria_1(ii) = 2.0 ^ ( time(ii) / double_time_1);
n_bacteria_2(ii) = 2.0 ^ ( time(ii) / double_time_2);

% Tell user
fprintf(' %6.1f%12.1f%12.1f\n',time(ii), ...
n_bacteria_1(ii), n_bacteria_2(ii));

end

% Plot colony size vs time


figure(1);
plot(time,n_bacteria_1,'b-','LineWidth',2);
hold on;
plot(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;

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;

When this program is executed, the results are:

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

% Script file: decibel2.m


%
% Purpose:
% To calculate the decibels referenced to 1 W for input
% powers of 1 to 20 W.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/02/15 S. J. Chapman Original code
%
% Define variables:
% dBW -- Power in dBW (dB referenced to 1 watt)
% pin -- Power in watts

% Get input power


pin = 1:1:20;

% Calculate dBm
dBW = 10 * log10( pin / 1.0 );

% Plot dBW vs power


figure(1);
semilogx(pin,dBW,'b-','LineWidth',2);
title('\bfPlot of dBW vs input power');
xlabel('\bfInput Power (W)');

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;

When this program is executed, the results are:

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.

% Script file: geometric_mean.m


%
% Purpose:
% To calculate the geometric mean of a set of positive
% numbers.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/02/15 S. J. Chapman Original code
%
% Define variables:
% x -- Input values
% g -- Geometric mean
% nvals -- Number of input values
% prod -- Product of input values

% Initialize product and nvals


prod = 1;
nvals = 0;

% Read the first number


121
© 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 = input('Enter first number: ');

% Read the remaining numbers


while x > 0
prod = prod * x;
nvals = nvals + 1;
x = input('Enter next number: ');
end

% Calculate geometric mean


g = prod ^ (1/nvals);

% Tell user
fprintf('The geometric mean is %.4f\n',g);

When this program is executed, the results are:

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

% Script file: rms_average.m


%
% Purpose:
% To calculate the rms average of a set of numbers.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/02/15 S. J. Chapman Original code
%
% Define variables:
% x -- Input values
% rms -- Rms average
% nvals -- Number of input values
% sum2 -- Sum of input values squared

% Initialize sum
sum2 = 0;

% Read the number of input values


nvals = input('Enter number of values: ');

% Read the numbers


for ii = 1:nvals
x = input('Enter number: ');

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

% Calculate rms average


rms = sqrt( sum2 / nvals );

% Tell user
fprintf('The rms average is %.4f\n',rms);

When this program is executed, the results are:

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

% Script file: harmonic_mean.m


%
% Purpose:
% To calculate the harmonic mean of a set of numbers.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code
%
% Define variables:
% hmean -- Harmonic mean
% nvals -- Number of input values
% sumr -- Sum of reciprocals of the input values
% x -- Input values

% Initialize sum
sumr = 0;

% Read the number of input values


nvals = input('Enter number of values: ');

% Read the numbers


for ii = 1:nvals
x = input('Enter number: ');
sumr = sumr + 1/x;
end

% Calculate harmonic mean


hmean = nvals / sumr;

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);

When this program is executed, the results are:

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

% Script file: all_means.m


%
% Purpose:
% To calculate the average (arithmetic mean), rms average,
% geometric mean, and harmonic mean of a set of numbers.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code
%
% Define variables:
% ave -- average
% g -- Geometric mean
% hmean -- Harmonic mean
% nvals -- Number of input values
% prod -- Product of input values
% rms -- Rms average
% sum -- Sum of input values
% sum2 -- Sum of input values squared
% sumr -- Sum of reciprocals of the input values
% x -- Input values

% Initialize sums
prod = 1;
sum = 0;
sumr = 0;
sum2 = 0;

% Read the number of input values


nvals = input('Enter number of values: ');

% Read the numbers


for ii = 1:nvals
x = input('Enter number: ');
prod = prod * x;
sum = sum + x;

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

% Calculate the means


ave = sum / nvals;
g = prod ^ (1/nvals);
hmean = nvals / sumr;
rms = sqrt( sum2 / nvals );

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

When this program is executed, the results are:

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

% Script file: mtbf.m


%
% Purpose:
% To calculate the MTBF of a system based on the MTBFs
% of its components.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code
%
% Define variables:
% mtbf -- Mean time between failure for overall system
% mtbfi -- MTBF for individual subsystems
% nvals -- Number of input values
% sumr -- Sum of reciprocals of the input values

% Initialize sum
sumr = 0;

% Read the number of input values


nvals = input('Enter number of subsystems: ');

% Read the numbers


for ii = 1:nvals
mtbfi = input(['Enter MTBF of Subsystem ' int2str(ii) ': ']);
sumr = sumr + 1/mtbfi;
end

% Calculate overall MTBF


mtbf = 1 / sumr;

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);

When this program is executed, the results are:

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

You might also like