Professional Documents
Culture Documents
MATLAB Programming For Engineers 5th Edition Chapman Solutions Manual Download
MATLAB Programming For Engineers 5th Edition Chapman Solutions Manual Download
In contrast, MATLAB functions are a special type of M-file that run in their own independent workspace.
They receive input data through an input argument list, and return results to the caller through an output
argument list.
6.2 MATLAB programs communicate with their functions using a pass-by-value scheme. When a function
call occurs, MATLAB makes a copy of the actual arguments and passes them to the function. This copying
is very significant, because it means that even if the function modifies the input arguments, it won’t affect
the original data in the caller. Similarly, the returned values are calculated by the function, and copied into
the return variables in the calling program.
6.3 The principal advantage of the pass-by-value scheme is that any changes to input arguments within a
function will not affect the input arguments in the calling program. This, along with the separate
workspace for the function, eliminates unintended side effects. The disadvantage is that copying
arguments, especially large arrays, can take time and memory.
6.4 A function to sort arrays in ascending or descending order, depending on the second calling parameter, is
shown below:
% Define variables:
% a -- Input array to sort
% ii -- Index variable
% iptr -- Pointer to min value
131
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% jj -- Index variable
% nvals -- Number of values in "a"
% out -- Sorted output array
% temp -- Temp variable for swapping
132
© 2016 Cengage Learning®. 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
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code
if sort_up
else
end
133
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% iptr now points to the min/max value, so swap a(iptr)
% with a(ii) if ii ~= iptr.
if ii ~= iptr
temp = a(ii);
a(ii) = a(iptr);
a(iptr) = temp;
end
end
% Preallocate array
array = zeros(1,nvals);
end
134
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Display the sorted result.
fprintf('\nSorted data in ascending order:\n');
for ii = 1:nvals
fprintf(' %8.4f\n',sorted1(ii));
end
» test_ssort1
Enter number of values to sort: 6
Enter value 1: -3
Enter value 2: 5
Enter value 3: 2
Enter value 4: 2
Enter value 5: 0
Enter value 6: 1
6.5 A set of functions to perform trigonometric operations in degrees are shown below:
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code
% Calculate value
out = sin(pi/180*x);
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code
136
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Calculate value
out = cos(pi/180*x);
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code
% Calculate value
out = tan(pi/180*x);
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code
% Calculate value
out = 180/pi * asin(x);
% Record of revisions:
% Date Programmer Description of change
137
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code
% Calculate value
out = 180/pi * acos(x);
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code
% Calculate value
out = 180/pi * atan(x);
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code
% Calculate value
out = 180/pi * atan2(y,x);
% Set the angle theta = 30 degrees, and try the forward trig functions
disp(' ');
disp(['Testing forward trig functions:']);
disp(['sind(30) = ' num2str(sind(30))]);
disp(['cosd(30) = ' num2str(cosd(30))]);
disp(['tand(30) = ' num2str(tand(30))]);
disp(['sind(45) = ' num2str(sind(45))]);
disp(['cosd(45) = ' num2str(cosd(45))]);
disp(['tand(45) = ' num2str(tand(45))]);
% Test atan2d
disp(' ');
disp(['Testing atan2d:']);
disp(['atan2d(4,3) = ' num2str(atan2d(4,3))]);
>> test_functions
This program tests the trig functions that return answers in degrees.
139
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Testing forward trig functions:
sind(30) = 0.5
cosd(30) = 0.86603
tand(30) = 0.57735
sind(45) = 0.70711
cosd(45) = 0.70711
tand(45) = 1
Testing atan2d:
atan2d(4,3) = 53.1301
% Define variables:
% deg_f -- Input in degrees Fahrenheit
% deg_c -- Output in degrees Celsius
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code
% Calculate value
deg_c = 5/9 * (deg_f - 32);
We can test this function using the freezing and boiling points of water:
>> f_to_c(32)
ans =
0
>> f_to_c(212)
ans =
100
140
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
6.7 A function to convert degrees Celsius to degrees Fahrenheit is shown below:
% Define variables:
% deg_c -- Input in degrees Celsius
% deg_f -- Output in degrees Fahrenheit
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code
% Calculate value
deg_f = 9/5 * deg_c + 32;
We can test this function using the freezing and boiling points of water:
>> f_to_f(0)
ans =
100
>> c_to_f(100)
ans =
0
We can also show that c_to_f and f_to_c are the inverses of each other:
>> f_to_c(c_to_f(30))
ans =
30
6.8 A function to calculate the area of a triangle specified by the locations of its three vertices is shown below:
% Define variables:
% x1, y1 -- Location of vertex 1
% x2, y2 -- Location of vertex 2
140
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% x3, y3 -- Location of vertex 3
% area -- Area of triangle
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code
% Calculate value
area = 0.5 * (x1*(y2-y3) - x2*(y1-y3) + x3*(y1-y2));
6.9 At this point in our studies, there is no general way to support an arbitrary number of arguments in a
function. Function nargin allows a developer to know how many arguments are used in a function call,
but we can only up to the number of arguments in the calling sequence1. We will design this function to
support up to 6 vertices. The corresponding function is shown below:
function area =
area_polygon(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6)
%AREA_POLYGON Calculate the area of a polygon specified by its vertices
% Function AREA_POLYGON calculates the area of a polygon specified by
% its vertices
%
% Calling sequence:
% area =
area_polygon(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6)
% Define variables:
% ii -- Loop index
% n_vertices -- Number of vetices in polygon
% x1, y1 -- Location of vertex 1
% x2, y2 -- Location of vertex 2
% x3, y3 -- Location of vertex 3
% x4, y4 -- Location of vertex 4
% x5, y5 -- Location of vertex 5
% x6, y6 -- Location of vertex 6
% area -- Area of polygon
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code
1 Later we will learn about function varargin, which can support any number of arguments.
141
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Check for a legal number of input arguments.
% There must be at least 3 vertices, and no more than 6.
msg = nargchk(6,12,nargin);
error(msg);
% Save values
x(1) = x1;
y(1) = y1;
x(2) = x2;
y(2) = y2;
x(3) = x3;
y(3) = y3;
if n_vertices >= 4
x(4) = x4;
y(4) = y4;
end
if n_vertices >= 5
x(5) = x5;
y(5) = y5;
end
if n_vertices >= 6
x(6) = x6;
y(6) = y6;
end
We can test this function using the specified point (0,0), (10,0), (10,10), and (0, 10), which corresponds to a
square with all sides having length 10:
We can test this function using the points specified in the problem:
142
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
>> area = area_polygon(10,0,8,8,2,10,-4,5)
area =
43.00
6.10 A function to calculate the inductance of a single-phase two-wire transmission line is shown below:
% Define variables:
% ind_per_m -- Inductance per meter
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code
% Constants
mu0 = pi * 4e-7; % H/m
We can test this function using the points specified in the problem:
6.11 If the diameter of a transmission line’s conductors increase, the inductance of the line will decrease. If the
diameter of the conductors are doubled, the inductance will fall to:
143
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
6.12 A function to calculate the capacitance of a single-phase two-wire transmission line is shown below:
% Define variables:
% cap_per_m -- Capacitance per meter
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code
% Constants
e0 = pi * 4e-7; % F/m
We can test this function using the points specified in the problem:
6.13 If the distance between the two conductors increases, the inductance of the transmission line increases and
the capacitance of the transmission line decreases.
6.14 A program to compare the sorting times using the selection sort of Example 6.2 and MATLAB’s built-in
sort is shown below:
% Constants
SIZE = 100000; % Number of values to sort
% Set seed
seed(123456);
>> compare_sorts
Sort time using ssort = 71.2407
Sort time using sort = 0.0060984
The built-in sorting function is dramatically faster than the selection sort of Example 6.2.
6.15 A program to compare the sorting times using the selection sort of Example 6.2 and MATLAB’s built-in
sort is shown below.
% Set seed
seed(123456);
146
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Display the relative times
disp(['Sort time for ' int2str(nsamp) ' using ssort =
' num2str(elapsed_time1)]);
disp(['Sort time for ' int2str(nsamp) ' using sort =
' num2str(elapsed_time2)]);
The built-in sorting function is dramatically faster than the selection sort of Example 6.2.
>> compare_sorts
Sort time for 10000 using ssort = 0.71161
Sort time for 10000 using sort = 0.000634
Sort time for 100000 using ssort = 70.9728
Sort time for 100000 using sort = 0.0036683
Sort time for 200000 using ssort = 286.6228
Sort time for 200000 using sort = 0.006115
The time for the selection sort is increasing roughly as the square of the number of samples being sorted.
For example, it takes 71 s for 100,000 samples, and 287 s for 200,000 samples. The number of samples
doubles, and the time goes up as 22. The MATLAB sort time increases much more slowly.
6.16 A modified version of function random0 that can accept 0, 1, or 2 arguments is shown below:
147
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Define variables:
% ii -- Index variable
% ISEED -- Random number seed (global)
% jj -- Index variable
% m -- Number of columns
% msg -- Error message
% n -- Number of rows
% ran -- Output array
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 02/04/14 S. J. Chapman Original code
% 1. 04/05/15 S. J. Chapman Modified for 0 arguments
6.17 Function random0 has a bug under some conditions. If the global variable ISEED has not been
previously defined when random0 is executed, the program will crash. This problem occurs the first time
only that random0 is executed in a given MATLAB session, if function seed is not called first. A simple
way to avoid this problem would be to detect if ISEED is undefined, and to supply a default value.
Otherwise, the function should use the global seed supplied. A modified version of random0 that fixes
this bug is shown below:
% Define variables:
% ii -- Index variable
% ISEED -- Random number seed (global)
% jj -- Index variable
% m -- Number of columns
% msg -- Error message
% n -- Number of rows
% ran -- Output array
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 02/04/14 S. J. Chapman Original code
% 1. 04/05/15 S. J. Chapman Modified to provide initial seed
6.18 A function dice to simulate the roll of a fair die is shown below:
149
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% die. It returns a random integer between 1
% and 6.
% Define variables:
% result -- Resulting integer
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/06/15 S. J. Chapman Original code
% Initial values
result = zeros(1,100000);
for ii = 1:100000;
result(ii) = dice;
end
» test_dice
The first 30 values are:
3 1 4 6 6 4 4 4 1 6 6 4 1 2 1 3 2 6 1 2 2 6 6 5 6 3 1 6 1 5
The resulting histogram is shown below. The histogram shows that each integer between 1 and 6 is about
equally likely to occur.
6.19 A function to calculate a probability from the Poisson distribution is shown below:
% Define variables:
% fact -- k! (k-factorial)
% result -- Resulting value from distribution
151
© 2016 Cengage Learning®. 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
% ==== ========== =====================
% 04/06/15 S. J. Chapman Original code
% Calculate k!
fact = factorial(k);
A program that uses function poisson to calculate the probability of a specific number of cars passing a
point on a highway in a given period of time is shown below:
% Display results
disp(['The probability of k cars passing in ' num2str(t)
' minutes is:']);
for k = 0:5
fprintf(' %3d %12.7f\n',k,prob(k+1));
end
152
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Now plot the distribution.
figure(1);
plot(0:5,prob,'bo','LineWidth',2);
title('\bfPoisson Distribution');
xlabel('\bfValue');
ylabel('\bfProbability');
When this program is executed, the results are a shown below. Note that the plot of the probability
distribution uses discrete points instead of a continuous line, since the probabilities are only defined for the
integer values k = 0, 1, 2, 3, … (we can’t have 1.2 cars go by!). This plot can also be represented as a bar
chart, once we learn how to create them in Chapter 6.
>> traffic
Enter expected number of cars/minute: 1.6
Enter period of time in minutes: 1
The probability of k cars passing in 1 minutes is:
0 0.2018965
1 0.3230344
2 0.2584275
3 0.1378280
4 0.0551312
5 0.0176420
6.20 Functions to calculate the hyperbolic sine, cosine, and tangent functions are shown below:
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/06/15 S. J. Chapman Original code
% Calculate value
out = (exp(x) - exp(-x))/2;
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/06/15 S. J. Chapman Original code
% Calculate value
out = (exp(x) + exp(-x))/2;
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 07/12/11 S. J. Chapman Original code
% Calculate value
out = (exp(x) - exp(-x)) ./ (exp(x) + exp(-x));
154
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
A script file to plot the hyperbolic sine, cosine, and tangent functions are shown below:
% Calculate results
x = -5:0.05:5;
out_cosh = cosh1(x);
out_sinh = sinh1(x);
out_tanh = tanh1(x);
% Display results
figure(1);
plot(x,out_cosh);
title('\bfHyperbolic cosine');
xlabel('\bfx');
ylabel('\bfcosh(x)');
grid on;
figure(2); plot(x,out_sinh);
title('\bfHyperbolic sine');
xlabel('\bfx');
ylabel('\bfsinh(x)');
grid on;
figure(3); plot(x,out_cosh);
title('\bfHyperbolic tangent');
xlabel('\bfx');
ylabel('\bftanh(x)');
grid on;
155
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
156
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
6.21 A function to smooth a noisy data set with a running average filter is shown below.
function y = running_ave(x,n_ave)
%RUNNING_AVE Function to perform a running average filter
% Function RUNNING_AVE performs a running average filter
%
% Calling sequence:
% y = running_ave(x, n_ave)
%
% where:
% n_ave -- Number of points to average
% x -- Array of input values
% y -- Array of filtered values
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/08/15 S. J. Chapman Original code
end
>> test_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
159
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
6.22 A function to smooth a noisy data set with a median filter is shown below.
function y = median_filter(x,n_ave)
%RUNNING_AVE Function to perform a median filter
% Function RUNNING_AVE performs a median filter
%
% Calling sequence:
% y = median_filter(x, n_ave)
%
% where:
% n_ave -- Number of points to average
% x -- Array of input values
% y -- Array of filtered values
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/08/15 S. J. Chapman Original code
160
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
msg = nargchk(1,2,nargin);
error(msg);
end
161
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
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: ');
>> test_median_filter
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
162
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
6.23 A function to sort an input data set into ascending order while carrying along another array is shown below.
% Define variables:
% a -- Input array to sort
% b -- Input array to carry along
% ii -- Index variable
% iptr -- Pointer to min value
% jj -- Index variable
% nvals -- Number of values in "a" and "b"
% out -- Sorted output array
% out2 -- Carried output array
% temp -- Temp variable for swapping
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/08/15 S. J. Chapman Original code
163
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
error(msg);
end
164
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% a -- Input data array to sort
% b -- Input data array to carry
% ii -- Index variable
% nvals -- Number of input values
% out1 -- Sorted data array
% out2 -- Carried data array
% Input arrays
a = [ 1, 11, -6, 17, -23, 0, 5, 1, -1];
b = [ 31,101, 36,-17, 0, 10, -8, -1, -1];
» test_sort_with_carry
Sorted data:
-23.0000 0.0000
-6.0000 36.0000
-1.0000 -1.0000
0.0000 10.0000
1.0000 31.0000
1.0000 -1.0000
5.0000 -8.0000
11.0000 101.0000
17.0000 -17.0000
6.24 A program to perform sort with carry using function sortrows is shown below.
165
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% nvals -- Number of input values
% out1 -- Sorted data array
% out2 -- Carried data array
% Input arrays
a = [ 1, 11, -6, 17, -23, 0, 5, 1, -1];
b = [ 31,101, 36,-17, 0, 10, -8, -1, -1];
c = [a' b'];
When this program is executed, the results are as shown below. The built-in function sortrows is much
more efficient than sort_with_carry!
>> test_sortrows
Sorted data:
-23.0000 0.0000
-6.0000 36.0000
-1.0000 -1.0000
0.0000 10.0000
1.0000 -1.0000
1.0000 31.0000
5.0000 -8.0000
11.0000 101.0000
17.0000 -17.0000
When this program is executed, the results are as shown below. The built-in function sortrows is much
more efficient than sort_with_carry!
» compare_sort_with_carry
sort_with_carry time = 4.4245
sortrows time = 0.01251
6.26 The geometry of this problem is shown below with respect to an arbitrary (x,y) reference system, where x is
the distance in the North direction and y is the distance in the East direction, forming a right-hand
coordinate system where is a compass angle. Note that the angles 1 and 2 are defined clockwise from
the North (x) axis (compass angles), and the bearings 1 and 2 are defined clockwise from the bow of the
ship. Note that the angles will be given in degrees, which is usual aboard ships.
167
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
With these definitions, the x location of the object can be defined as the sum of the distance from the origin
to Ship 1 ( x1a ) plus the distance from Ship 1 to the object ( x1b ), and the y location of the object can be
defined as the sum of the distance from the origin to Ship 1 ( y1a ) plus the distance from Ship 1 to the
object ( y1b ).
x x1a x1b x1a r1 cos 1 1 (6.1)
Similarly, then the x location of the object can be defined as the sum of the distance from the origin to Ship
2 ( x2a ) plus the distance from Ship 2 to the object ( x2b ), and the y location of the object can be defined as
the sum of the distance from the origin to Ship 2 ( y2a ) plus the distance from Ship 2 to the object ( y2b ).
x x2a x2b x2a r2 cos 2 2 (6.3)
The range r2 and bearing 2 of the target from Ship 2 can be calculated by first determining the (x,y)
position of the target using Equations (5.1) and (5.2), and then calculating the range and bearing by solving
Equations (5.3) and (5.4) as follows:
r x x 2 y y 2 (6.5)
2 2a 2a
168
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
yy2a
tan 1 (6.6)
2
x x2a 2
A function to calculate the range and bearing as seen by Ship 2 is shown below:
% Define variables:
% phi1 -- Bearing of target from Ship 1 (degrees)
% phi2 -- Bearing of target from Ship 2 (degrees)
% r1 -- Range of target from Ship 1
% r2 -- Range of target from Ship 2
% theta1 -- Heading of Ship 1 (degrees)
% theta2 -- Heading of Ship 2 (degrees)
% x -- x-pos of target in global coordinate system
% x1 -- x-pos of Ship 1
% x2 -- x-pos of Ship 2
% y -- y-pos of target in global coordinate system
% y1 -- y-pos of Ship 1
% y2 -- y-pos of Ship 2
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/09/15 S. J. Chapman Original code
169
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Convert output bearing to degrees
171
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
phi2 = phi2 * 180/pi;
% Display result
fprintf('Ship 2 sees the target at a range of %.1f\n', r2);
fprintf('Ship 2 sees the target at a bearing of %.1f deg\n', phi2);
To test this function, we will try three simple cases. First, suppose that the two ships are in the same place
and moving in the same direction. Then the object should be at the same range and bearing for both ships.
170
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
>> test_range_bearing
x-pos of Ship 1: 0
y-pos of Ship 1: 0
Heading of Ship 1 (deg): 0
x-pos of Ship 2: 0
y-pos of Ship 2: 0
Heading of Ship 2 (deg): 0
Range to target from Ship 1: 5
Bearing to target from Ship 1: 30
Ship 2 sees the target at a range of 5.0
Ship 2 sees the target at a bearing of 30.0 deg
This case produced the correct answer. Now, suppose that the two ships are traveling North in line abreast,
with Ship 1 at (0,0) and Ship 2 at (0,5). If Ship 1 sees the object at a range of 5 and an angle of 30, then
Ship 2 should see the object at the same range and an angle of -30, because the y-distance to the target is
2.5, exactly half of the distance between the two ships.
>> test_range_bearing
x-pos of Ship 1: 0
y-pos of Ship 1: 0
Heading of Ship 1 (deg): 0
x-pos of Ship 2: 0
y-pos of Ship 2: 5
Heading of Ship 2 (deg): 0
Range to target from Ship 1: 5
Bearing to target from Ship 1: 30
Ship 2 sees the target at a range of 5.0
Ship 2 sees the target at a bearing of -30.0 deg
This case also produced the correct answer. Finally, suppose that the ships are in the same position, but Ship
2 has a heading of 30. In this case, the target should be at a bearing of -60 as seen by Ship 2, because
the ship itself has rotated.
» test_range_bearing
x-pos of Ship 1: 0
y-pos of Ship 1: 0
Heading of Ship 1 (deg): 0
x-pos of Ship 2: 0
y-pos of Ship 2: 5
Heading of Ship 2 (deg): 30
Range to target from Ship 1: 5
Bearing to target from Ship 1: 30
Ship 2 sees the target at a range of 5.0
Ship 2 sees the target at a bearing of -60.0 deg
6.27 A function that calculates the linear least-squares fit to an input data set is shown below:
171
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% the same length, and must contain at least two elements.
%
% The calling sequence is:
% [slope,yint] = lsqfit(x,y);
%
% where
% slope = the slope of the fitted line
% yint = y-intercept of the fitted line
% x = Input x values
% y = Input y values
% Define variables:
% sum_x -- Sum of values in x
% sum_x2 -- Sum of values in x.^2
% sum_xy -- Sum of values in x.*y
% sum_y -- Sum of values in y
% xbar -- Average of x
% ybar -- Average of y
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/09/15 S. J. Chapman Original code
% Check to make sure that the two vectors are the same length
if length(x) ~= length(y)
error('Vectors x and y must be the same length!');
end
A test program for this function is shown below. Note that this program also uses function polyfit to
compare against.
172
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Script file: test_lsqfit.m
%
% Purpose:
% To test the function lsqfit.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/09/15 S. J. Chapman Original code
%
% Define variables:
% slope -- Slope of fitted line
% x -- Input x values
% x1 -- x values of fitted line
% y -- Input y values
% y1 -- y values of fitted line
% yint -- Y-intercept of fitted line
% Tell user
fprintf('\n%s\n','Using lsqfit.m:');
fprintf('%s%7.3f\n','Slope = ',slope);
fprintf('%s%7.3f\n','Intercept = ',yint);
>> test_lsqfit
173
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Using lsqfit.m:
Slope = 1.858
Intercept = 0.187
6.28 Modified program to plot the residuals of the least squares fit in the previous problem is shown below:
174
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
-2.83 -1.16 0.52 0.21 1.73 3.96 4.26 ...
5.75 6.67 7.70 7.31 9.05 10.95 ];
% Tell user
fprintf('\n%s\n','Using lsqfit.m:');
fprintf('%s%7.3f\n','Slope = ',slope);
fprintf('%s%7.3f\n','Intercept = ',yint);
>> test_lsqfit
Using lsqfit.m:
Slope = 1.858
Intercept = 0.187
175
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
The residuals seem to be rougly balanced above and below the fitted line, so this appears to be a pretty
good fit.
176
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
6.29 Function random1 produces samples from a uniform random distribution on the range [-1,1).
% Define variables:
% m -- Number of columns
% n -- Number of rows
% ran -- Output array
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code
When this function is tested, the results are in the range [-1,1) and look reasonably uniformly distributed:
>> random1(20,1)
ans =
-0.9100
0.2498
0.9814
0.6669
-0.0876
-0.5937
0.7752
-0.5582
-0.5179
0.4820
0.3948
177
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
0.3984
-0.2477
0.6547
-0.9002
-0.2652
0.7172
0.5717
-0.9524
-0.0242
6.30 A function to calculate random values from a Gaussian normal distribution is shown below:
% Define variables:
% ii, jj -- Loop index
% m -- Number of row
% n -- Number of columns
% r -- sqrt of v1^2 + v2^2
% res -- Results
% v1, v2 -- Uniform random variables in [-1,1)
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code
% Calculate data
res = zeros(n,m);
for ii = 1:n
for jj = 1:m
% Get 2 uniform random variables in the range
178
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% [-1.,1.) such that the square root of the sum
% of their squares < 1. Keep trying until we
% come up with such a combination.
v1 = 2. * rand(1,1) - 1;
v2 = 2. * rand(1,1) - 1;
r = v1.^2 + v2.^2;
while (r >= 1)
v1 = 2. * rand(1,1) - 1;
v2 = 2. * rand(1,1) - 1;
r = v1.^2 + v2.^2;
end
% Calculate a Gaussian random variable from the
% uniform variables:
res(ii,jj) = sqrt( -2. * log(r) / r ) * v1;
end
end
The following program tests random_normal by creating 1000 random samples, and checking the mean and
standard deviation of the distribution. The mean should theoretically be 0.0 and the standard deviation
should theoretically be 1.0.
% Tell user
fprintf('Average = %.4f\n',ave);
fprintf('Std Dev = %.4f\n',sd);
% Create histogram
hist(dist,9);
title('\bfHistogram of random values');
179
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
xlabel('\bfValue');
ylabel('\bfCount');
>> test_random_normal
Average = 0.0259
Std Dev = 1.0249
6.31 A function to calculate the force of gravity between two objects is shown below:
180
© 2016 Cengage Learning®. 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
% ==== ========== =====================
% 04/07/15 S. J. Chapman Original code
% Gravitational constant
gravc = 6.672E-11;
% Calculate force
force = gravc .* m1 .* m2 ./ range.^2;
% Calculate force
fprintf('The force due to gravity is %0.4f N.\n', ...
gravity(range,m1,m2));
>> test_gravity
Enter mass of object 1 (kg): 800
Enter mass of object 2 (kg): 6.98e24
Enter range between objects (m): 38e6
The force due to gravity is 258.0086 N.
181
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
6.32 A function to calculate random values from a Rayleigh distribution is shown below:
% Define variables:
% arr1 -- Normally-distributed array
% arr2 -- Normally-distributed array
% res -- Results
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/07/15 S. J. Chapman Original code
% Calculate data
arr1 = randn(n,m);
arr2 = randn(n,m);
res = sqrt( arr1.^2 + arr2.^2 );
The following program tests random_rayleigh by creating 20,0000 random samples, and checking the
mean and standard deviation of the distribution.
182
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% 04/07/15 S. J. Chapman Original code
%
% Define variables:
% ave -- Average (mean) of distribution
% dist -- Distribution
% sd -- Standard deviation of distribution
% Tell user
fprintf('Average = %.4f\n',ave);
fprintf('Std Dev = %.4f\n',sd);
% Create histogram
hist(dist,21);
title('\bfHistogram of random values');
xlabel('\bfValue');
ylabel('\bfCount');
>> test_random_rayleigh
Average = 1.2490
Std Dev = 0.6517
183
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
184
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.