Essentials of MATLAB Programming 3rd Edition Chapman Solutions Manual instant download all chapter

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 78

Essentials of MATLAB Programming

3rd Edition Chapman Solutions Manual


Go to download the full and correct content document:
https://testbankdeal.com/product/essentials-of-matlab-programming-3rd-edition-chap
man-solutions-manual/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

MATLAB Programming for Engineers 5th Edition Chapman


Solutions Manual

https://testbankdeal.com/product/matlab-programming-for-
engineers-5th-edition-chapman-solutions-manual/

MATLAB Programming with Applications for Engineers 1st


Edition Chapman Solutions Manual

https://testbankdeal.com/product/matlab-programming-with-
applications-for-engineers-1st-edition-chapman-solutions-manual/

Introduction to MATLAB 3rd Edition Etter Solutions


Manual

https://testbankdeal.com/product/introduction-to-matlab-3rd-
edition-etter-solutions-manual/

Introduction to MATLAB Programming and Numerical


Methods for Engineers 1st Edition Siauw Solutions
Manual

https://testbankdeal.com/product/introduction-to-matlab-
programming-and-numerical-methods-for-engineers-1st-edition-
siauw-solutions-manual/
Matlab A Practical Introduction to Programming and
Problem Solving 4th Edition Attaway Solutions Manual

https://testbankdeal.com/product/matlab-a-practical-introduction-
to-programming-and-problem-solving-4th-edition-attaway-solutions-
manual/

MATLAB A Practical Introduction to Programming and


Problem Solving 5th Edition Attaway Solutions Manual

https://testbankdeal.com/product/matlab-a-practical-introduction-
to-programming-and-problem-solving-5th-edition-attaway-solutions-
manual/

Engineers Guide To MATLAB 3rd Edition Magrab Solutions


Manual

https://testbankdeal.com/product/engineers-guide-to-matlab-3rd-
edition-magrab-solutions-manual/

Digital Signal Processing using MATLAB 3rd Edition


Schilling Solutions Manual

https://testbankdeal.com/product/digital-signal-processing-using-
matlab-3rd-edition-schilling-solutions-manual/

Essentials of Economics 3rd Edition Krugman Solutions


Manual

https://testbankdeal.com/product/essentials-of-economics-3rd-
edition-krugman-solutions-manual/
6. Basic User-Defined Functions
6.1 Script files are just collections of MATLAB statements that are stored in a file. When a script file is
executed, the result is the same as it would be if all of the commands had been typed directly into
the Command Window. Script files share the Command Window’s workspace, so any variables that
were defined before the script file starts are visible to the script file, and any variables created by the
script file remain in the workspace after the script file finishes executing. A script file has no input
arguments and returns no results, but script files can communicate with other script files through the
data left behind in the workspace.

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:

function out = ssort1(a,dir)


%SSORT1 Selection sort data in ascending or descending order
% Function SSORT1 sorts a numeric data set into ascending
% or descending order, depending on the value of the
% second parameter. If the parameter is 'up', then it
% sorts the data in ascending order. If the parameter is
% 'down', then it sorts the data in descending order. The
% default value is 'up'. Note that 'up' and 'down' may
% be abbreviated to 'u' and 'd', if desired.
%
% Note that the selection sort is relatively inefficient.
% DO NOT USE THIS FUNCTION FOR LARGE DATA SETS. Use MATLAB's
% "sort" function instead.

% Define variables:
% a -- Input array to sort
% ii -- Index variable
% iptr -- Pointer to min value
% jj -- Index variable
% nvals -- Number of values in "a"
% out -- Sorted output array
% temp -- Temp variable for swapping
129
© 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
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(1,2,nargin);
error(msg);

% If the direction argument is missing, set it to 'up'.


if nargin < 2
dir = 'up';
end

% Check for the direction of the sort


if dir(1) == 'u' | dir(1) == 'U'
sort_up = 1;
elseif dir(1) == 'd' | dir(1) == 'D'
sort_up = 0;
else
error('Second parameter is not ''UP'' or ''DOWN''!')
end

% Get the length of the array to sort


nvals = size(a,2);

% Sort the input array


for ii = 1:nvals-1

if sort_up

% Sort in ascending order.


% Find the minimum value in a(ii) through a(n)
iptr = ii;
for jj = ii+1:nvals
if a(jj) < a(iptr)
iptr = jj;
end
end

else

% Sort in descending order.


% Find the maximum value in a(ii) through a(n)
iptr = ii;
for jj = ii+1:nvals
if a(jj) < a(iptr)
iptr = jj;
end
end

end

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

% Pass data back to caller


out = a;

A script file to test this function is shown below:

% Script file: test_ssort1.m


%
% Purpose:
% To read in an input data set, sort it into ascending
% order using the selection sort algorithm, and to
% write the sorted data to the Command window. This
% program calls function "ssort1" to do the actual
% sorting.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code
%
% Define variables:
% array -- Input data array
% ii -- Index variable
% nvals -- Number of input values
% sorted1 -- Sorted data array (up)
% sorted2 -- Sorted data array (down)

% Prompt for the number of values in the data set


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

% Preallocate array
array = zeros(1,nvals);

% Get input values


for ii = 1:nvals

% Prompt for next value


string = ['Enter value ' int2str(ii) ': '];
array(ii) = input(string);

end

% Now sort the data in ascending order


sorted1 = ssort1(array,'up');

131
© 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.
% Display the sorted result.
fprintf('\nSorted data in ascending order:\n');
for ii = 1:nvals
fprintf(' %8.4f\n',sorted1(ii));
end

% Now sort the data in descending order


sorted2 = ssort1(array,'down');

% Display the sorted result.


fprintf('\nSorted data in descending order:\n');
for ii = 1:nvals
fprintf(' %8.4f\n',sorted2(ii));
end

% Now sort the data in ascending order with


% no second argument.
sorted3 = ssort1(array);

% Display the sorted result.


fprintf('\nSorted data in default order:\n');
for ii = 1:nvals
fprintf(' %8.4f\n',sorted3(ii));
end

% The follwing call should produce an error message


sorted4 = ssort1(array,'bad');

When this program is executed, the results are:

» 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

Sorted data in ascending order:


-3.0000
0.0000
1.0000
2.0000
2.0000
5.0000

Sorted data in descending order:


-3.0000
0.0000
1.0000
2.0000

132
© 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.
2.0000
5.0000

Sorted data in default order:


-3.0000
0.0000
1.0000
2.0000
2.0000
5.0000
??? Error using ==> ssort1
Second parameter is not 'UP' or 'DOWN'!

Error in ==> C:\data\book\matlab_essentials\3e\soln\Ex5.4\test_ssort1.m


On line 66 ==>

6.5 A set of functions to perform trigonometric operations in degrees is shown below:

function out = sind(x)


%SIND Calculate sin(x), where x is in degrees
% Function SIND calculates sin(x), where x is in degrees
%
% Define variables:
% x -- Angle in degrees

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(1,1,nargin);
error(msg);

% Calculate value
out = sin(pi/180*x);

function out = sind(x)


%COSD Calculate cos(x), where x is in degrees
% Function COSD calculates cos(x), where x is in degrees
%
% Define variables:
% x -- Angle in degrees

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(1,1,nargin);
error(msg);

133
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Calculate value
out = cos(pi/180*x);

function out = tand(x)


%TAND Calculate tan(x), where x is in degrees
% Function TAND calculates tan(x), where x is in degrees
%
% Define variables:
% x -- Angle in degrees

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(1,1,nargin);
error(msg);

% Calculate value
out = tan(pi/180*x);

function out = asind(x)


%ASIND Calculate asin(x), where the output is in degrees
% Function ASIND calculates asin(x), where the output is in degrees
%
% Define variables:
% x -- Input value

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(1,1,nargin);
error(msg);

% Calculate value
out = 180/pi * asin(x);

function out = acosd(x)


%ACOSD Calculate acos(x), where the output is in degrees
% Function ACOSD calculates acos(x), where the output is in degrees
%
% Define variables:
% x -- Input value

% Record of revisions:

134
© 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.
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(1,1,nargin);
error(msg);

% Calculate value
out = 180/pi * acos(x);

function out = atand(x)


%ATAND Calculate atan(x), where the output is in degrees
% Function ATAND calculates atan(x), where the output is in degrees
%
% Define variables:
% x -- Input value

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(1,1,nargin);
error(msg);

% Calculate value
out = 180/pi * atan(x);

function out = atan2d(y,x)


%ATAN2D Four quadrant inverse tangent, where the output is in degrees
% Function ATAN2D calculates the Four quadrant inverse tangent, where
% the output is in degrees.
%
% Define variables:
% x -- Input value

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(2,2,nargin);
error(msg);

% Calculate value
out = 180/pi * atan2(y,x);

A script file to test these functions is given below:

135
© 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: test_functions.m
%
% Purpose:
% To perform a median filter on an input data set.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/03/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 tests the trig functions that return answers in


degrees.');

% 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 the inverse trig functions


disp(' ');
disp(['Testing inverse trig functions:']);
disp(['asind(0) = ' num2str(asind(0))]);
disp(['asind(1/sqrt(2)) = ' num2str(asind(1/sqrt(2)))]);
disp(['asind(1) = ' num2str(asind(1))]);
disp(['acosd(0) = ' num2str(acosd(0))]);
disp(['acosd(1/sqrt(2)) = ' num2str(acosd(1/sqrt(2)))]);
disp(['acosd(1) = ' num2str(acosd(1))]);
disp(['atand(1) = ' num2str(atand(1))]);

% Test atan2d
disp(' ');
disp(['Testing atan2d:']);
disp(['atan2d(4,3) = ' num2str(atan2d(4,3))]);

When the script file is executed, the results are:

>> test_functions

136
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
This program tests the trig functions that return answers in degrees.

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 inverse trig functions:


asind(0) = 0
asind(1/sqrt(2)) = 45
asind(1) = 90
acosd(0) = 90
acosd(1/sqrt(2)) = 45
acosd(1) = 0
atand(1) = 45

Testing atan2d:
atan2d(4,3) = 53.1301

6.6 A function to convert degrees Fahrenheit to degrees Celsius is shown below:

function deg_c = f_to_c(deg_f)


%F_TO_C Convert degrees Fahrenheit to degrees Celsius
% Function F_TO_C converts degrees Fahrenheit to degrees Celsius
% %
% Calling sequence:
% deg_c = f_to_c(deg_f)

% 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

% Check for a legal number of input arguments.


msg = nargchk(1,1,nargin);
error(msg);

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

137
© 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.
ans =
100

6.7 A function to convert degrees Celsius to degrees Fahrenheit is shown below:

function deg_f = c_to_f(deg_c)


%C_TO_F Convert degrees Celsius to degrees Fahrenheit
% Function C_TO_F converts degrees Celsius to degrees Fahrenheit
% %
% Calling sequence:
% deg_f = c_to_f(deg_c)

% 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

% Check for a legal number of input arguments.


msg = nargchk(1,1,nargin);
error(msg);

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

function area = area2d(x1, y1, x2, y2, x3, y3)


%AREA2D Calculate the area of a triangle specified by three vertices
% Function AREA2D calculates the area of a triangle specified by
% three vertices
%
% Calling sequence:
% area = area2d(x1, y1, x2, y2, x3, y3)

138
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Define variables:
% x1, y1 -- Location of vertex 1
% x2, y2 -- Location of vertex 2
% 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

% Check for a legal number of input arguments.


msg = nargchk(6,6,nargin);
error(msg);

% Calculate value
area = 0.5 * (x1*(y2-y3) - x2*(y1-y3) + x3*(y1-y2));

We can test this function using the specified points:

>> area = area2d(0,0,10,0,15,5)


area =
25.00

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

1 Later we will learn about function varargin, which can support any number of arguments.
139
© 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.
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code

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

% Get the number of vertices


n_vertices = nargin / 2;

% Save vertices in arrays


x = zeros(1,n_vertices);
y = zeros(1,n_vertices);

% 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

% Calculate the area


area = 0;
for ii = 1:n_vertices-2
area = area + 0.5 * (x(ii)*(y(ii+1)-y(ii+2)) ...
- x(ii+1)*(y(ii)-y(ii+2)) ...
+ x(ii+2)*(y(ii)-y(ii+1)));
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:

>> area = area_polygon(0,0,10,0,10,10,0,10)


area =
100.00

We can test this function using the points specified in the problem:

>> area = area_polygon(0,0,10,0,10,10,0,10)

140
© 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.
area =
100.00
>> 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:

function ind = inductance(r, D, length)


%INDUCTANCE Calculate the inductance of a transmission line
% Function INDUCTANCE calculates the inductance of a
% single-phase two-wire transmission line.
%
% Calling sequence:
% ind = inductance(r, D, length)
%
% where
% r = the radius of the conductors in meters
% D = the distance between the two lines in meters
% length = Length of transmission line in meters

% Define variables:
% ind_per_m -- Inductance per meter

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(3,3,nargin);
error(msg);

% Constants
mu0 = pi * 4e-7; % H/m

% Calculate the inductance


ind_per_m = mu0 / pi * (1/4 + log(D/r));

% Get the inductance


ind = ind_per_m * length;

We can test this function using the points specified in the problem:

>> ind = inductance(0.02, 1.5, 100000)


ind =
0.1827

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:

>> ind = inductance(0.02, 1.5, 100000)


ind =

141
© 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.1550

6.12 A function to calculate the capacitance of a single-phase two-wire transmission line is shown below:

function cap = capacitance(r, D, length)


%CAPACITANCE Calculate the capacitance of a transmission line
% Function CAPACITANCE calculates the capacitance of a
% single-phase two-wire transmission line.
%
% Calling sequence:
% cap = capacitance(r, D, length)
%
% where
% r = the radius of the conductors in meters
% D = the distance between the two lines in meters
% length = Length of transmission line in meters

% Define variables:
% cap_per_m -- Capacitance per meter

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(3,3,nargin);
error(msg);

% Constants
e0 = pi * 4e-7; % F/m

% Calculate the capacitance


cap_per_m = pi * e0 / log((D-r)/r);

% Get the capacitance


cap = cap_per_m * length;

We can test this function using the points specified in the problem:

>> cap = capacitance(0.04, 1.5, 100000)


cap =
0.1097

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:

% Script file: compare_sorts.m


%
% Purpose:

142
© 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.
% To compare the sort function from Example 6.2 and the
% built-in MATLAB sort
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code
%
% Define variables:
% data1 -- Array to sort
% data2 -- Copy of array to sort
% elapsed_time1 -- Elapsed time for ssort
% elapsed_time2 -- Elapsed time for sort

% Constants
SIZE = 100000; % Number of values to sort

% Set seed
seed(123456);

% Create a sample data set to sort.


data1 = random0(1,SIZE);

% Sort using ssort


data2 = data1;
tic;
out = ssort(data2);
elapsed_time1 = toc;

% Sort using sort


data2 = data1;
tic;
out = sort(data2);
elapsed_time2 = toc;

% Display the relative times


disp(['Sort time using ssort = ' num2str(elapsed_time1)]);
disp(['Sort time using sort = ' num2str(elapsed_time2)]);

When this program is executed, the results are:

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

% Script file: compare_sorts.m


%
% Purpose:

143
© 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.
% To compare the sort function from Example 6.2 and the
% built-in MATLAB sort
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 07/04/11 S. J. Chapman Original code
%
% Define variables:
% data1 -- Array to sort
% data2 -- Copy of array to sort
% elapsed_time1 -- Elapsed time for ssort
% elapsed_time2 -- Elapsed time for sort

% Set seed
seed(123456);

% Create a sample data set to sort


nsamp = 10000;
data1 = random0(1,nsamp);

% Sort using ssort


data2 = data1;
tic;
out = ssort(data2);
elapsed_time1 = toc;

% Sort using sort


data2 = data1;
tic;
out = sort(data2);
elapsed_time2 = toc;

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

% Create a sample data set to sort


nsamp = 100000;
data1 = random0(1,nsamp);

% Sort using ssort


data2 = data1;
tic;
out = ssort(data2);
elapsed_time1 = toc;

% Sort using sort


data2 = data1;
tic;
out = sort(data2);
elapsed_time2 = toc;

144
© 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.
% 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)]);

% Create a sample data set to sort


nsamp = 200000;
data1 = random0(1,nsamp);

% Sort using ssort


data2 = data1;
tic;
out = ssort(data2);
elapsed_time1 = toc;

% Sort using sort


data2 = data1;
tic;
out = sort(data2);
elapsed_time2 = toc;

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

function ran = random0(n,m)


%RANDOM0 Generate uniform random numbers in [0,1)
% Function RANDOM0 generates an array of uniform
% random numbers in the range [0,1). The usage
% is:
%
% random0(n) -- Generate an n x n array
% random0(n,m) -- Generate an n x m array

% Define variables:
% ii -- Index variable
% ISEED -- Random number seed (global)

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

% Declare global values


global ISEED % Seed for random number generator

% Check for a legal number of input arguments.


msg = nargchk(0,2,nargin);
error(msg);

% If both arguments are missing, set to 1.


% If the m argument is missing, set it to n.
if nargin < 1
m = 1;
n = 1;
elseif nargin < 2
m = n;
end

% Initialize the output array


ran = zeros(n,m);

% Now calculate random values


for ii = 1:n
for jj = 1:m
ISEED = mod(8121*ISEED + 28411, 134456 );
ran(ii,jj) = ISEED / 134456;
end
end

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:

function ran = random0(n,m)


%RANDOM0 Generate uniform random numbers in [0,1)
% Function RANDOM0 generates an array of uniform
% random numbers in the range [0,1). The usage
% is:
%
% random0(n) -- Generate an n x n array

146
© 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.
% random0(n,m) -- Generate an n x m array

% 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

% Declare globl values


global ISEED % Seed for random number generator

% Check for a legal number of input arguments.


msg = nargchk(1,2,nargin);
error(msg);

% If the m argument is missing, set it to n.


if nargin < 2
m = n;
end

% Initialize the output array


ran = zeros(n,m);

% Test for missing seed, and supply a default if necessary.


if isempty(ISEED)
ISEED = 99999;
end

% Now calculate random values


for ii = 1:n
for jj = 1:m
ISEED = mod(8121*ISEED + 28411, 134456 );
ran(ii,jj) = ISEED / 134456;
end
end

6.18 A function dice to simulate the roll of a fair die is shown below:

function result = dice()


%DICE Return a random integer between 1 and 6
% Function DICE simulates the throw of a fair
% die. It returns a random integer between 1
% and 6.

147
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Define variables:
% result -- Resulting integer

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/06/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(0,0,nargin);
error(msg);

% The value "6*random0(1,1)" returns a value


% in the range [0,6). The "floor" function
% returns {0,1,2,3,4,5} with equal probability,
% so "result" returns 1-6.
result = floor( 6 * random0(1,1) ) + 1;

A script file to test function dice is shown below:

% Script file: test_dice.m


%
% Purpose:
% To test the function dice. This function calls dice
% 10,000 times, and examines the distribution of the
% resulting values. They should be roughly uniform.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/06/15 S. J. Chapman Original code
%
% Define variables:
% ii -- index variable
% result -- Array of results

% Initial values
result = zeros(1,100000);
for ii = 1:100000;
result(ii) = dice;
end

% Display the first 30 values.


fprintf('The first 30 values are:\n');
for ii = 1:30
fprintf('%d ',result(ii));
end
fprintf('\n');

% Now calculate a histogram to determine the overall


% distribution of numbers.
hist(result,6);
title('\bfHistogram of values returned from function "dice"');

148
© 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.
xlabel('\bfValue');
ylabel('\bfCount');

When this script file is executed, the results are:

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

function result = poisson(k, t, lambda)


%POISSON Return a random integer between 1 and 6
% Function POISSON calculates a sample value from
% the Poisson distribution for specific values of
% k, t, and lambda.

% Define variables:
% fact -- k! (k-factorial)
% result -- Resulting value from distribution

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================

149
© 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.
% 04/06/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(3,3,nargin);
error(msg);

% Calculate k!
fact = factorial(k);

% Calculate value from Poisson distribution.


result = exp(-lambda*t) * (lambda*t) ^ k / fact;

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:

% Script file: traffic.m


%
% Purpose:
% To calculate the probability of a given number of cars
% passing a particular point on a highway in a given time.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/06/15 S. J. Chapman Original code
%
% Define variables:
% k -- Actual number of cars in time t
% lambda -- Expected number of cars per minute
% prob -- Probability array
% t -- Period of time (minutes)

% Get initial values


lambda = input('Enter expected number of cars/minute: ');
t = input('Enter period of time in minutes: ');

% Calculate values. Note that k runs from 0 to 5, while the


% minimum value for a MATLAB array is 1, so we must index into
% the MATLAB array using "k+1" instead of "k".
for k = 0:5
prob(k+1) = poisson(k, t, lambda);
end

% 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

% Now plot the distribution.


figure(1);
plot(0:5,prob,'bo','LineWidth',2);
title('\bfPoisson Distribution');

150
© 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.
xlabel('\bfValue');
ylabel('\bfProbability');

When this program is executed, the results are as 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:

function out = sinh(x)


%SIND Calculate hyperbolic sine function
% Function SINH calculates the hyperbolic sine function
%
% Define variables:
% x -- Input value

% Record of revisions:
% Date Programmer Description of change

151
© 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.
% ==== ========== =====================
% 04/06/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(1,1,nargin);
error(msg);

% Calculate value
out = (exp(x) - exp(-x))/2;

function out = cosh1(x)


%COSH1 Calculate hyperbolic cosine function
% Function COSH1 calculates the hyperbolic cosine function
%
% Define variables:
% x -- Input value

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/06/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(1,1,nargin);
error(msg);

% Calculate value
out = (exp(x) + exp(-x))/2;

function out = tanh1(x)


%TANH1 Calculate hyperbolic tangent function
% Function TANH1 calculates the hyperbolic tangent function
%
% Define variables:
% x -- Input value

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 07/12/11 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(1,1,nargin);
error(msg);

% Calculate value
out = (exp(x) - exp(-x)) ./ (exp(x) + exp(-x));

A script file to plot the hyperbolic sine, cosine, and tangent functions are shown below:

% Script file: test_hyperbolic_functions.m


%
% Purpose:

152
© 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.
% To plot the hyperbolic functions sinh, cosh, abd tanh.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/06/15 S. J. Chapman Original code
%
% Define variables:
% out_cosh -- Hyperbolic cosine
% out_sinh -- Hyperbolic sine
% out_tanh -- Hyperbolic tangent

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

The resulting plots are shown below:

153
© 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.
154
© 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.
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

% Define local variables:


% ii -- Loop index
% n_per_side -- Number of points to average per side
% n_points -- Number of points in data set
% slope -- Slope of the line

% Check for a legal number of input arguments.


msg = nargchk(1,2,nargin);

155
© 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.
error(msg);

% Set a default number of points to average if this value


% is undefined.
if nargin < 2
n_ave = 7;
end

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

% Get the number of points in the input structure


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

A program to test this function is shown below.

% Script file: test_running_ave.m


%
% Purpose:
% To perform test the running average filter function.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/08/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
% x -- Array of input values
% y -- Array of filtered values

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


disp('input data set.');

156
© 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.
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.
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);

% Get running average


y = running_ave(x,n_ave);

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

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

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

% Define local variables:


% ii -- Loop index
% n_per_side -- Number of points to average per side
% n_points -- Number of points in data set
% slope -- Slope of the line

% Check for a legal number of input arguments.


msg = nargchk(1,2,nargin);
158
© 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.
error(msg);

% Set a default number of points to average if this value


% is undefined.
if nargin < 2
n_ave = 7;
end

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

% Get the number of points in the input structure


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

A program to test this function is shown below.

% Script file: test_median_filter.m


%
% Purpose:
% To test the median filter function.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/08/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.');

159
© 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.
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.
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 median filter


y = median_filter(x,n_ave);

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

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

160
© 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.
6.23 A function to sort an input data set into ascending order while carrying along another array is shown
below.

function [out1, out2] = sort_with_carry(a,b)


%SORT_WITH_CARRY Selection sort with carry in ascending order
% Function SORT_WITH_CARRY sorts a numeric data set a into
% ascending order, carrying along array b. Note that the
% selection sort is relatively inefficient. DO NOT USE THIS
% FUNCTION FOR LARGE DATA SETS.

% 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

% Check for a legal number of input arguments.

161
© 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.
msg = nargchk(2,2,nargin);
error(msg);

% Check for a legal length. Both a and b must be


% the same length.
if length(a) ~= length(b)
error('Vectors a and b must be the same length');
end

% Get the length of the array to sort


nvals = length(a);

% Sort the input array


for ii = 1:nvals-1

% Find the minimum value in a(ii) through a(n)


iptr = ii;
for jj = ii+1:nvals
if a(jj) < a(iptr)
iptr = jj;
end
end

% iptr now points to the minimum value, so swap a(iptr)


% with a(ii) if ii ~= iptr.
if ii ~= iptr
temp = a(ii);
a(ii) = a(iptr);
a(iptr) = temp;
temp = b(ii);
b(ii) = b(iptr);
b(iptr) = temp;
end

end

% Pass data back to caller


out1 = a;
out2 = b;

A program to test this function is shown below:

% Script file: test_sort_with_carry.m


%
% Purpose:
% To read in an input data set a and sort it into
% ascending order while carrying along array b.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/08/15 S. J. Chapman Original code
%

162
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Define variables:
% 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];

% Now sort the data


[out1, out2] = sort_with_carry(a,b);

% Display the sorted result.


fprintf('\nSorted data:\n');
for ii = 1:length(a)
fprintf(' %8.4f %8.4f\n',out1(ii),out2(ii));
end

When this program is executed, the results are:

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

% Script file: test_sortrows.m


%
% Purpose:
% To read in an input data set a and sort it into
% ascending order while carrying along array b.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/08/15 S. J. Chapman Original code
%
% Define variables:
% a -- Input data array to sort
% b -- Input data array to carry
% c -- Compislte matrix

163
© 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.
% 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];
c = [a' b'];

% Now sort the data


c = sortrows(c);

% Display the sorted result.


fprintf('\nSorted data:\n');
for ii = 1:length(a)
fprintf(' %8.4f %8.4f\n',c(ii,1),c(ii,2));
end

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

6.25 A program to compare sort_with_carry with sortrows is shown below.

% Script file: compare_sort_with_carry.m


%
% Purpose:
% To compare function sort_with_carry with function
% sortrows.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/08/15 S. J. Chapman Original code
%
% Define variables:
% a -- Input data array to sort
% array -- Input data for sortrows
% b -- Input data array to carry
% ii -- Index variable

164
© 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.
% nvals -- Number of input values
% out -- Output data for sortrows
% out1 -- Sorted data array
% out2 -- Carried data array

% Create random arrays


array = rand(25000,2);

% Make copy for sort_with_carry


a = array(:,1);
b = array(:,2);

% Sort using sort_with_carry


tic;
[out1, out2] = sort_with_carry(a,b);
disp(['sort_with_carry time = ',num2str(toc)]);

% Sort using sortrows


tic;
out = sortrows(array,1);
disp(['sortrows time = ',num2str(toc)]);

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.

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

y = y1a + y1b = y1a + r1 sin (θ1 + φ1 ) (6.2)

Similarly, 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 = x2 a + x2b = x2 a + r2 cos (θ 2 + φ2 ) (6.3)

y = y2 a + y2b = y2 a + r2 sin (θ 2 + φ2 ) (6.4)

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:

r2 = ( x − x2 a ) 2 + ( y − y 2 a ) 2 (6.5)

166
© 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.
 y − y2 a 
φ2 = tan −1  − θ2 (6.6)
 x − x2 a 

A function to calculate the range and bearing as seen by Ship 2 is shown below:

function [r2, phi2] = range_bearing(x1,y1,theta1,r1,phi1, ...


x2,y2,theta2)
%RANGE_BEARING Calculate the range and bearing of a target from a ship
% Function RANGE_BEARING calculates the range and bearing of a
% target from a ship, given the location, range, and bearing of
% the target from another ship.

% 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

% Check for a legal number of input arguments.


msg = nargchk(8,8,nargin);
error(msg);

% Convert input angles to radians for use with trig functions


theta1 = theta1 * pi/180;
theta2 = theta2 * pi/180;
phi1 = phi1 * pi/180;

% Calculate the (x,y) position of the target in the


% coordinate system.
x = x1 + r1 * cos( theta1 + phi1 );
y = y1 + r1 * sin( theta1 + phi1 );

% Get range to target from Ship 2


r2 = sqrt( (x - x2)^2 + (y - y2)^2 );

% Get bearing of target from ship


phi2 = atan2( y - y2, x - x2 ) - theta2;

% Convert output bearing to degrees

167
© 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.
phi2 = phi2 * 180/pi;

A script file to test this function is shown below:

% Script file: test_range_bearing.m


%
% Purpose:
% To test function range_bearing.m
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/09/15 S. J. Chapman Original code
%
% 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)
% x1 -- x-pos of Ship 1
% x2 -- x-pos of Ship 2
% y1 -- y-pos of Ship 1
% y2 -- y-pos of Ship 2

% Get location of Ship 1 (x,y,theta):


x1 = input('x-pos of Ship 1: ');
y1 = input('y-pos of Ship 1: ');
theta1 = input('Heading of Ship 1 (deg): ');

% Get location of Ship 2 (x,y,theta):


x2 = input('x-pos of Ship 2: ');
y2 = input('y-pos of Ship 2: ');
theta2 = input('Heading of Ship 2 (deg): ');

% Get location of target as seen by Ship 1


r1 = input('Range to target from Ship 1: ');
phi1 = input('Bearing to target from Ship 1: ');

% Calculate range and bearing from Ship 2


[r2, phi2] = range_bearing( x1, y1, theta1, r1, phi1, ...
x2, y2, theta2 );

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

>> test_range_bearing

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

This function appears to be working properly.

6.27 A function that calculates the linear least-squares fit to an input data set is shown below:

function [slope, yint] = lsqfit(x, y)


%LSQFIT Calculate the linear least squares fit to a data set.
% Function LSQFIT calculates the linear least squares fit line
% to an input data set. Note that vectors x and y must be
% the same length, and must contain at least two elements.

169
© 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 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 for a legal number of input arguments.


msg = nargchk(2,2,nargin);
error(msg);

% 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

% Check to ensure that there are at least two elements


if length(x) < 2
error('Vectors x and y must be at least 2 elements long!');
end

% Now calculate sums


sum_x = sum(x);
sum_y = sum(y);
sum_x2 = sum(x.^2);
sum_xy = sum(x .* y);

% Calculate slope and intercept


xbar = sum_x / length(x);
ybar = sum_y / length(y);
slope = (sum_xy - sum_x * xbar) / (sum_x2 - sum_x * xbar);
yint = ybar - slope * xbar;

A test program for this function is shown below. Note that this program also uses function
polyfit to compare against.

% Script file: test_lsqfit.m

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

% Input data values


x = [-4.91 -3.84 -2.41 -2.62 -3.78 -0.52 -1.83 ...
-2.01 0.28 1.08 -0.94 0.59 0.69 3.04 ...
1.01 3.60 4.53 5.13 4.43 4.12 ];
y = [-8.18 -7.49 -7.11 -6.15 -5.62 -3.30 -2.05 ...
-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 ];

% Get fitted line


[slope, yint] = lsqfit(x,y);
x1(1) = min(x);
x1(2) = max(x);
y1 = slope*x1 + yint;

% Tell user
fprintf('\n%s\n','Using lsqfit.m:');
fprintf('%s%7.3f\n','Slope = ',slope);
fprintf('%s%7.3f\n','Intercept = ',yint);

% Plot points and the fitted line


figure(1);
plot(x,y,'bo','LineWidth',2);
hold on;
plot(x1,y1,'k-','LineWidth',2);
legend ('Input data','Fitted line');
title('\bfLinear Least-Squares Fit Using Lsqfit');
xlabel('\bf\itx');
ylabel('\bf\ity');
grid on;
hold off;

The resulting plots are shown below:

>> test_lsqfit

Using lsqfit.m:

171
© 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.
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:

% 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:
% ii -- Loop index
% 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

% Input data values


x = [-4.91 -3.84 -2.41 -2.62 -3.78 -0.52 -1.83 ...
-2.01 0.28 1.08 -0.94 0.59 0.69 3.04 ...
1.01 3.60 4.53 5.13 4.43 4.12 ];
y = [-8.18 -7.49 -7.11 -6.15 -5.62 -3.30 -2.05 ...
172
© 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.
-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 ];

% Get fitted line


[slope, yint] = lsqfit(x,y);
x1(1) = min(x);
x1(2) = max(x);
y1 = slope*x1 + yint;

% Tell user
fprintf('\n%s\n','Using lsqfit.m:');
fprintf('%s%7.3f\n','Slope = ',slope);
fprintf('%s%7.3f\n','Intercept = ',yint);

% Plot points and the fitted line


figure(1);
plot(x,y,'bo','LineWidth',2);
hold on;
plot(x1,y1,'k-','LineWidth',2);
legend ('Input data','Fitted line');
title('\bfLinear Least-Squares Fit Using Lsqfit');
xlabel('\bf\itx');
ylabel('\bf\ity');
grid on;
hold off;

% Now calculate the residuals of the fit


res = zeros(length(x));
for ii = 1:length(x)
res(ii) = y(ii) - (slope*x(ii) + yint);
end

% Plot residuals
figure(2);
plot(x,res,'bo','LineWidth',2);
title('\bfResiduals of Fit');
xlabel('\bf\itx');
ylabel('\bf\ity');
grid on;

The resulting plots are shown below:

>> test_lsqfit

Using lsqfit.m:
Slope = 1.858
Intercept = 0.187

173
© 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 residuals seem to be rougly balanced above and below the fitted line, so this appears to be a
pretty good fit.

174
© 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.
6.29 Function random1 produces samples from a uniform random distribution on the range [-1,1).

function ran = random1(n,m)


%RANDOM1 Generate uniform random numbers in [1,1)
% Function RANDOM1 generates an array of uniform
% random numbers in the range [1,1). The usage
% is:
%
% random1() -- Generate a single value
% random1(n) -- Generate an n x n array
% random1(n,m) -- Generate an n x m array

% 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

% Check for a legal number of input arguments.


msg = nargchk(1,2,nargin);
error(msg);

% If both arguments are missing, set to 1.


% If the m argument is missing, set it to n.
if nargin < 1
m = 1;
n = 1;
elseif nargin < 2
m = n;
end

% Initialize the output array


ran = 2 * random0(n,m) - 1;

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

175
© 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.3948
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:

function res = random_normal(n,m)


%RANDOM_NORMAL Return samples from a normal distribution.
% Function RANDOM_NORMAL generates an array of gaussian
% normal random numbers. The usage is:
%
% random_normal() -- Generate a single value
% random_normal(n) -- Generate an n x n array
% random_normal(n,m) -- Generate an n x m array
%

% 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

% Check for a legal number of input arguments.


msg = nargchk(0,2,nargin);
error(msg);

% If both arguments are missing, set to 1.


% If the m argument is missing, set it to n.
if nargin < 1
m = 1;
n = 1;
elseif nargin < 2
m = n;
end

% Calculate data
res = zeros(n,m);
for ii = 1:n
for jj = 1:m

176
© 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 2 uniform random variables in the range
% [-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.

% Script file: test_random_normal.m


%
% Purpose:
% To test function random_normal by getting 1000 random
% normal values, calculating the mean and standard
% deviation, and plotting a histogram of the values.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/05/15 S. J. Chapman Original code
%
% Define variables:
% ave -- Average (mean) of distribution
% dist -- Distribution
% sd -- Standard deviation of distribution

% Get 1000 values


dist = random_normal(1,1000);

% Calculate mean and standard deviation


ave = mean(dist);
sd = std(dist);

% Tell user
fprintf('Average = %.4f\n',ave);
fprintf('Std Dev = %.4f\n',sd);

% Create histogram

177
© 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.
hist(dist,9);
title('\bfHistogram of random values');
xlabel('\bfValue');
ylabel('\bfCount');

When this program is executed, the results are:

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

function force = gravity(range,m1,m2)


%GRAVITY Return force of gravity between two masses.
% Function GRAVITY calculates the gravitation force
% between two objects separated by a specified range.
% The usage is:
%
% force = gravity(range,m1,m2);
% where
% range -- range in meters
% m1 -- Mass of object 1 in kilograms
% m2 -- Mass of object 2 in kilograms
% force -- Force in newtons

% Define local variables:


% gravc -- Gravitational constant
178
© 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.
% m -- Number of row

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/07/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(3,3,nargin);
error(msg);

% Gravitational constant
gravc = 6.672E-11;

% Calculate force
force = gravc .* m1 .* m2 ./ range.^2;

A program to test this function is shown below:

% Script file: test_gravity.m


%
% Purpose:
% To test the gravitational force calculation.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/07/15 S. J. Chapman Original code
%
% Define variables:
% m1 -- Mass of body 1, in kg
% m2 -- Mass of body 2, in kg
% range -- Distance between objects, in m

% Get input values


m1 = input('Enter mass of object 1 (kg): ');
m2 = input('Enter mass of object 2 (kg): ');
range = input('Enter range between objects (m): ');

% Calculate force
fprintf('The force due to gravity is %0.4f N.\n', ...
gravity(range,m1,m2));

When this program is executed, the results are:

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

6.32 A function to calculate random values from a Rayleigh distribution is shown below:

179
© 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.
function res = random_rayleigh(n,m)
%RANDOM_RAYLEIGH Return samples from a Rayleigh distribution.
% Function RANDOM_RAYLEIGH generates an array of Rayleigh-
% distributed random numbers. The usage is:
%
% random_rayleigh() -- Generate a single value
% random_rayleigh(n) -- Generate an n x n array
% random_rayleigh(n,m) -- Generate an n x m array
%

% 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

% Check for a legal number of input arguments.


msg = nargchk(0,2,nargin);
error(msg);

% If both arguments are missing, set to 1.


% If the m argument is missing, set it to n.
if nargin < 1
m = 1;
n = 1;
elseif nargin < 2
m = n;
end

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

% Script file: test_random_rayleigh.m


%
% Purpose:
% To test function random_rayleigh by getting 20,000
% values, calculating the mean and standard
% deviation, and plotting a histogram of the values.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/07/15 S. J. Chapman Original code
%

180
© 2018 Cengage Learning®. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Define variables:
% ave -- Average (mean) of distribution
% dist -- Distribution
% sd -- Standard deviation of distribution

% Get 20,000 values


dist = random_rayleigh(1,20000);

% Calculate mean and standard deviation


ave = mean(dist);
sd = std(dist);

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

When this program is executed, the results are:

>> test_random_rayleigh
Average = 1.2490
Std Dev = 0.6517

181
© 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.
182
© 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.
Another random document with
no related content on Scribd:
The Project Gutenberg eBook of The wellsprings
of space
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: The wellsprings of space

Author: Albert Teichner

Illustrator: Dan Adkins

Release date: March 21, 2024 [eBook #73226]

Language: English

Original publication: New York, NY: Ziff-Davis Publishing Company,


1961

Credits: Greg Weeks, Mary Meehan and the Online Distributed


Proofreading Team at http://www.pgdp.net

*** START OF THE PROJECT GUTENBERG EBOOK THE


WELLSPRINGS OF SPACE ***
Like oases in the desert, they
were spaced through the universe
to replenish the electron-thirst
of the giant ships. But Old
Huddleston had seen the problem:
What kind of currency
serves to buy matter from ...

The WELLSPRINGS OF SPACE

By ALBERT TEICHNER

Illustrated by ADKINS

[Transcriber's Note: This etext was produced from


Amazing Stories October 1961.
Extensive research did not uncover any evidence that
the U.S. copyright on this publication was renewed.]
The three top scientists had come to describe their greatest triumph
to the revered Huddleston; after centuries of bitter disagreement the
world's cosmologists were now unanimous in accepting the newly-
proposed Lowen-Crane-and-Fitzhugh Hypothesis. At three hundred
Huddleston was doddering toward death but the great man certainly
deserved to know in his more lucid moments that the problems he
had outlined long ago were finally solved. He had been the first to
prophesy that all parsec journeys to the stars must fail because each
spaceship would steadily lose electrons to the weak magnetic field of
the galaxy. The few weakened shells that had managed to limp back
into the solar system had proven his point.
He was having one of his brighter periods when they came in. Not
only were his eyes and wrinkled flesh glowing with pink health (the
illusory super-health of the very aged) but he knew instantly who
they were. "My best pupils!" he chuckled, curling his plasti-patched
lips. "May your lives be as long and as happy as mine has been."
Lowen, four-square solid and close to seven feet in height, almost
automatically became the spokesman for the trio. "We have the best
news of all for your final phase," he said with bluff kindliness. "The
electron leakage problem has been solved."
The old man's eyes widened and a network of hairfine lines
proliferated around them. "It can't be done," he said, wistfully gazing
out his window at the night sky, then at the shelves of antique bottles
that ringed the room. "We're the eternal prisoners of the solar
system. You shouldn't tease an old man."
They exchanged knowingly sympathetic glances. None of them
could ever be the great pioneer that he had been but even a midget
standing on a giant's shoulder could see further than the giant
himself.
"We now know there is continuous creation of matter out in space."
Lowen paused dramatically for the point to sink in but the ancient
only continued to look incredulous. He hurried on. "It was simply a
matter of incorrect methodology, Learned Master. We have always
assigned too many of the decision-functions in this area to
computers when it was too purely a creative problem for anything but
human minds."

Huddleston had suddenly become serious. "That could make a


difference. Well, I haven't given a moment's thought to the whole
matter for fifty years—much too exhausting when you're having so
many prosthetic operations, much nicer to putter around with
hobbies like old maps and bottles—but, gentlemen, just before I
gave up, oh now it's clear as if it were yesterday! I remember
thinking what you've just said: This problem's too basic for
automated analysis. If I'd only been less tired; but, by then—."
"You'd already done more than your share," Fitzhugh consoled him.
"And we have more precise instruments now. The big breakthrough
came on the data from the newest Jupiter observatory. Every once in
a while it would pick up unaccountable Doppler shifts from the
direction of Arcturus but the disturbing area was too small for an
accurate fix at such a distance. That was the beginning—Crane and
I worked out the rest. But Lowen made the great practical
achievement. Together we achieved a hypothesis that proves
beyond any question that the universe has no beginning, will have
no end and is constantly receiving new matter as it expands, matter
from other dimensions—in a word, continuous creation."
"You can imagine the uproar at first," Lowen grinned, "especially
since the big-bang theory has held the field for two centuries. That's
why we had to tell you quickly—you never surrendered your mind to
any dogma, always kept it open."
Huddleston spryly took the sheaf of reports that Lowen had been
holding and started to glance rapidly through them. "Brilliant, brilliant!
What I'd give to be young again."
"You'll tire yourself," Fitzhugh said. "We didn't expect you to do an
analysis."
"Nonsense," the old man snapped waspishly. "This gives me new
life, just seeing what you youngsters are up to. Of course, though,
continuous creation can't make any difference as far as parsec travel
is concerned."
"But it does!" they all shouted.
Huddleston laughed. "Now, now, gentlemen. Just because hydrogen
atoms are springing into being from nothingness throughout space
doesn't mean—."
"That's not how it is," Crane said, speaking down to Huddleston as if
he were the tallest man in the room, not the shortest. "Lowen has
shown that continuous creation does not take place everywhere.
That's his great practical discovery and—"
"It happens at specific, restricted points," Lowen broke in. "Great
streams of hydrogen and free electrons welling into our universe the
way water does out of dry ground."
Huddleston let the report slip from his hands onto a table and stared
at them. He was very pale now. "My God, I think I see what you're
getting at."
They considered each other, bewildered by his reaction to such good
news. "You must be missing the real point, Learned Master," said
Lowen. "The wellsprings are spaced at approximately one million
parsecs apart. I've already pinpointed hundreds of them. We
established the first one from the Jupiter readings and the rest
practically mapped themselves out. It has checked out a dozen
different ways. That was one place where the computers could
handle the job—on the checkout." He tapped the report with his
thumb. "Nodes of lifesaving electrons across the deepest reaches of
space—."
"—where each spaceship can bathe its weakened structure,"
suggested Huddleston, "refill every lattice gap where electrons have
dropped out."
"Exactly. You still can always see to the heart of the matter, Learned
Master."
Huddleston sank into a chair, shaking his head as if dazed. "It won't
work."
"Why not?" they demanded, astounded.
"I don't know. I just know that it can't work. You never get something
for nothing. What would you lose at each wellspring?"
"Nothing!" Lowen insisted. "You see, the ship's structure would be
strengthened as the empty electron positions were refilled. Then we
would shift back into hyperdrive and move on to the next wellspring.
The ancient systems of caravan waterholes but on a cosmic scale."

The old man pounded the table energetically. "No, no! Oh, I'm willing
to accept your calculations as far as they go. You were all excellent
students and have had distinguished careers and you're in your
eighties at the first peak of vigor. But nothing can be this convenient.
I sense that the problem lies—." He was chalk-white now, his hands
shaking. "Lies in those maps of ancient Manhattan. Did Broadway go
into Grand Central or stop at North Michigan Avenue? Annie, Annie,"
he shouted, "where are the subway maps?"
His niece came running into the room, carrying some rare antique
maps, and gasped as she saw him. "You'll all have to go," she
whispered. "I've never seen him this bad before."
"Here, uncle, here are your favorite maps." He took them from her
with quivering fingers, mumbling something about it being time.
"One more question," Lowen persisted.
She whirled on him, anger making her look much younger than her
nearly two centuries. "Get out of here, the whole bunch of you—
distinguished men! Haven't you the sense to see how he is? All he
wants now is his little hobby."
"But we have to get an explanation from him," Crane protested. "It's
very import—."
Fitzhugh tugged at his elbow. "Forget it, Crane. His mind's far away
now."
They retreated to the door. Eunice Huddleston gave them one sharp
glance, then turned back to her uncle who was slipping into sleep,
his face still deathly pale.
They stopped in the garden outside the great man's house and
Crane shook his head, worried. "I'd give a lot to know what he was
thinking about."
Lowen thumped his back encouragingly. "He was a very great man
but, well, after three hundred years, he's entitled to the special
pleasures of senility."
"He seemed so lucid for a while," Fitzhugh said, "I mean when he
saw the point of moving through the wellspring nodes to overcome
materials fatigue." He shrugged. "No, you're right, Lowen. We'll have
to go to the President without Huddleston's backing."
"I was thinking about his prestige. But his support really wouldn't
have proven anything." Lowen shook his head. "I had no idea he had
gone downhill that much in the last twenty years."
They joined in a sympathetic sigh for past greatness, then hurried on
to the business of the future.

President Collins was pleased to see them. He was even happier


when he was shown how the recent, highly-publicized discovery of
the space nodes of continuous creation could be put to practical use.
"There's a serious sociological problem that this can solve for us,
gentlemen. You probably haven't given it much attention since your
interests lie in other directions."
"We leave that to our political leaders," Lowen nodded. "They're
thoroughly competent to do so."
"Thank you, Professor,—."
"No, President Collins, you're right—I don't have time to bother with
imprecise life studies." Lowen tried to keep contempt out of his grin.
"A little entertainment, somewhat more theory and lots of practical
technical applications—that's my personal prescription for staying
fully alive."
"Anyway your work fits the present social bill to a T," President
Collins went on, choosing to disregard the unpleasant aspects of his
visitor's one-sided nature for the pleasant fruits they had borne. "For
close to two centuries now we have known we were trapped in the
general area of the solar system and society has learned to live with
the limitation. But lately an indefinable restlessness has been
growing—nothing in the least serious but it's there and continuous
entertainment, study and sports just aren't enough to eliminate it.
This renewed outward movement can, though. I'm backing your
request for a new Stellar Reaches Expedition to the limit of my
strength." He rubbed his chin, smiling sadly. "You know who we
ought to get in touch with? Old Huddleston. He deserves to know.
Come to think of it, his opinion would still carry plenty of weight with
many people."
"We've told him," Lowen announced. "He was enormously impressed
with the solution."
"Good, good. Now, there's an ultimate Master, if I ever heard of one,
knowledge in every area, the humanities, mathematics, logic, poetry,
physics—. What did he think about fatigued metal revival at the
wellsprings?"
Lowen squinted. "Sad thing, Mister President, we couldn't get much
of an opinion there. He's so worn-out." Lowen disregarded Fitzhugh's
conscience-stricken look. "But he did grasp what we told him before
he relapsed."
"It is a sad thing, isn't it? Well, the years get us all one way or the
other, don't they?"
"I guess so," said Lowen, "but, Mr. Pres—."
Collins perked up. "Tell you what, though—he's liable to get a clear
period any time and we really should have his thinking on this. I'll
have that niece of his notify my office as soon as it happens and we'll
go right over."
"He's in very bad shape," Lowen hastened to say. "It would just wear
him down more."
"That bad, heh? Then I'd better make certain we get to see him very
soon."
Lowen glared at the floor, ready to kick himself for aggravating an
already touchy situation.
The intervideo snapped on. "Could you come out for a moment?" his
secretary whispered on screen. She looked very upset.
"Certainly, Helen, I'll be right there." President Collins turned to them.
"I hope you gentlemen will excuse me."
"Of course, Mister President." They all rose and bowed slightly in his
direction.
"Maps," President Collins smiled just before he went out. "That's his
big hobby now, isn't it? Wonder what I'll go in for when I reach the
intermittent senile phase?" He grinned. "Oh well, I still have a
century before that."
As soon as the door shut, Lowen whirled on his associates. "What
the hell's the matter with you two? You looked as if you were going to
spill the whole beans about the old man. We have to watch our
step."
"But the implication about his reaction was somewhat distorted,"
Fitzhugh protested.
"Somewhat distorted! Well, what of it? The most innocent little
distortion I ever heard! We don't even know what Huddleston really
means, do we?"
"That's what I mean by distorted, Lowen. You didn't convey that
impression—."
Lowen exploded. "You're making me sick! You too, Crane, you
looked qualmish." He leaned forward, spitting his words through
clenched teeth. "The hypocrisy of it—you'd lie to your own soul if
anything got in the way of this project. But now you can make nice
prissy postures because I'm doing the so-called dirty work for you."
Fitzhugh waved for calm. "Agreed, agreed, Lowen, it is much more
important than a squeamish little point."
"Much more important," seconded Crane.
Collins made a grim-faced return. "I have news from Huddleston's
niece."
The three men tensed. "What—," asked Lowen.
"Gentlemen, you were right about the seriousness of his condition.
He's dead. She said he became so excited about something you had
told him that he had a serious relapse. He started to babble
incoherently and never returned to articulate speech."
They leaned back, more relaxed. "A terrible blow," said Crane. "The
least we can do is carry forward his work."
"You're absolutely right." Tired, he rubbed his silver eye-brows for a
moment. "Gentlemen, I'll see to it that the Expedition gets every bit
of support it needs."

The next month was one of unaccustomed excitement for the


tranquilly routine existence of human society. First the death of the
one survivor of the earliest generation of Learned Masters and then
the announcement about the renewed thrust to the stars that was to
be enacted by the three men who had made it possible. There was
talk for a time of constructing a larger ship that could carry a full crew
complement but Lowen's arguments had quickly overcome such
objections. For one thing, design and execution of the project would
take many years. For another, it would require vast expenditures
even in the preliminary stages. "Of course, the effort is worth any
amount eventually," Lowen had been the first to emphasize, "but why
not wait until we see what the results are from the smaller design
first?"
"Very reasonable," President Collins had agreed. "You three have
sacrificed your own interests far beyond the call of duty."
This devotion reinforced his decision to have the three men named
Learned Masters before their theory was put to the ultimate test, a
move that had been hopefully anticipated in their calculations. Here,
though, some public opposition did develop. "No one has ever been
named a Learned Master under the age of one hundred and fifty," a
few people pointed out. "Now, suddenly, we are told three men, none
of them more than eighty-five, should be so honored! Even the great
Huddleston never had that."
But President Collins expressed the feelings of the overwhelming
majority of citizens when he said, "The successful accomplishment
of the task these men have set themselves will be an even greater
achievement than that of their first teacher." His viewpoint prevailed
and, after much grumbling, the Solar Institute of Learning
unanimously confirmed their nomination for supreme honors.
The ceremony took place four months after construction on the New
Cosmos had begun and was celebrated in the great hall of the
Institute. The world's most important figure in each major field of
thought, usually a doddering oldster, gave a confirming speech; and
the accompanying three-D explanations enthralled billions who
suddenly discovered how bored they had been for the past century.
The only flaw in an otherwise glorious day of festivities was the
refusal of Eunice Huddleston to participate. She issued no public
statement but they knew well enough that she still insisted they had
somehow upset her uncle and that, if his death could not have been
avoided, his final moments could have at least been happier ones
without their intrusion.
Her abstention almost upset Fitzhugh. "Still," he managed to console
himself, "she'll see the matter in a different light once we get back."
Lowen, though, remained altogether undisturbed by the
development. "I feel like a distinguished oldster and like a vigorous
youngster both at the same time. Learned Master—oh, my
colleagues, how we've managed to speed things up!"
"Which just goes to prove," Crane laughed, "that you really can have
your cake and eat it."
Planning the flight was much simpler than it seemed to the non-
specialist public. Very little of a new nature had to be added to the
ship's design beyond what had been known for a long time. And
there was no doubt that hyperdrive speeds far beyond those of light
were possible if the proper carrier components were selected from
those that averaged out to the normal 186,000-mile limit. That had
been mastered a long time ago. The only doubt had been about the
ability to return. Now that was dispelled and they could safely plan to
reach a point close to the galactic center and return within seven
weeks. No calculations had been left to chance; the survey of all
known factors showed that it was no more dangerous than a journey
within the solar system—and that certainly was routine by now.
If anything, popular enthusiasm increased the longer the project
lasted. Thousands of men threw themselves into the round-the-clock
effort and nine months after construction had commenced the great
sleek ship was ready.

The New Cosmos took off on a morning of bright spring sunlight but,
instead of immediately moving onto special carrier components,
stuck to solar velocities so that they first could make a triumphal tour
of the system. Approaching Mars, they were met by a great fleet of
commuting liners, rising to greet them with an enormous display of
atomic fireworks, and in their circuit of Saturn they were treated to a
special auroral display. Then, two days later, the last planet behind
them, they moved into hyperdrive, heading for the first node of
continuous creation.
Crane made his hundredth re-check and said, "We'll be there in forty
minutes."
Outside the nearer stars had become tiny beeps of light, visible only
for miniseconds, and only those of the farther reaches accompanied
them fixedly on their way. Lowen gave regular two-minute interval
readings of structural fatigue. "The electron loss is within one part in
a million of estimate—and the error is in our favor. We can proceed
five hours without danger."
Fitzhugh beamed his contentment. "So much margin of safety—it's a
beautiful universe!"
They established voice contact with Earth on the carrier components
and spoke all at once into the receiver as the "Are you all right?"
query came: "Never better!" they shouted.
Lowen was the first to pull himself out of their attack of space
ecstasy. "We will start sending data following the first node," he
intoned. "Twenty minutes to first report."
Then, suddenly, they were entering the area of continuous creation
and looked out with awe on the one mystery in the universe that was
even greater than that of life itself. The electron loss started to ease
off at an accelerating rate, reached balance and finally moved into
active acquisition. All around them the latticework of matter that was
the New Cosmos was filling up again. They hurried to their assigned
stations and intently studied the readings until the ship, as good as
new, had passed beyond the initial wellspring.
Crane was the first to notice. After staring, hypnotized, at the master
dial before him he suddenly became aware of his hand resting on
the console below it. "My God!" he croaked.
They turned to look at each other in horror. "Turn back!" Lowen
shrieked.
"We can't," Fitzhugh moaned, "it's set for the next node." He
struggled desperately with his console and shouted into the sender,
"Top Secret Scramble to President Collins, Top—." He fought to get
the words out. "We're reversing back as soon as possible. It's all
wrong. This way won't work. I can't talk much longer," he wheezed.
"I've set for automatic return after the next wellspring. My God, it was
so beautiful and it is so horrible. We're heading straight into the next
wellspring now. It—."
Then the contact went dead.

Five hours later the great ship, undamaged, made a perfect


automatic landing at the precise point from which it had left. Collins
and a staff from the Institute were already waiting there, nervously
wondering whether they would really have to start looking for a new
approach to the star travel problem. "They have to be all right," he
said, as the ship came down. "It's in perfect shape. Probably some
space hallucination."
As they moved toward the craft, the exit hatch opened and three
wizened men came creeping out, leaning forward as if they were
resting on canes. Their individual differences were barely
distinguishable beneath the levelling networks of wrinkles but they
were giggling hysterically.
"Old bottles!" Lowen kept cackling and each time he said it Crane
and Fitzhugh joined him in wild laughter.
Collins stared, wide-eyed. "What was it?" he said.
Lowen squinted at him and there was the slightest glint of
recognition as he became briefly lucid. "Ah yes! We didn't get it for
nothing. We had to pay with—." The glint disappeared and he
laughed. "Old bottles! I'm going to have the biggest collection in the
world."
"What happened?" Collins pleaded, knowing even then that he
would never get another rational word from any of them.
"Me too! Old bottles!"
"Collect them! Maybe maps too!"
"They've gone insane and they've become diseased," said a man
from the Institute, shrinking back in disgust.
"No, not that, not really that. It's something else—They're only very
old."
And in the split second of his saying that last word Collins knew what
it was, what they had paid with. It was the only thing with which you
could buy matter—Time.
THE END
*** END OF THE PROJECT GUTENBERG EBOOK THE
WELLSPRINGS OF SPACE ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying copyright
royalties. Special rules, set forth in the General Terms of Use part of
this license, apply to copying and distributing Project Gutenberg™
electronic works to protect the PROJECT GUTENBERG™ concept
and trademark. Project Gutenberg is a registered trademark, and
may not be used if you charge for an eBook, except by following the
terms of the trademark license, including paying royalties for use of
the Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is very
easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE

You might also like