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

MATLAB Programming with

Applications for Engineers 1st Edition


Chapman Solutions Manual
Go to download the full and correct content document:
https://testbankfan.com/product/matlab-programming-with-applications-for-engineers-
1st-edition-chapman-solutions-manual/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

MATLAB Programming for Engineers 5th Edition Chapman


Solutions Manual

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

Essentials of MATLAB Programming 3rd Edition Chapman


Solutions Manual

https://testbankfan.com/product/essentials-of-matlab-
programming-3rd-edition-chapman-solutions-manual/

Introduction to MATLAB Programming and Numerical


Methods for Engineers 1st Edition Siauw Solutions
Manual

https://testbankfan.com/product/introduction-to-matlab-
programming-and-numerical-methods-for-engineers-1st-edition-
siauw-solutions-manual/

MATLAB for Engineers 5th Edition Moore Solutions Manual

https://testbankfan.com/product/matlab-for-engineers-5th-edition-
moore-solutions-manual/
MATLAB for Engineers 4th Edition Moore Solutions Manual

https://testbankfan.com/product/matlab-for-engineers-4th-edition-
moore-solutions-manual/

Applied Numerical Methods with MATLAB for Engineers and


Scientists 2nd Edition Steven Chapra Solutions Manual

https://testbankfan.com/product/applied-numerical-methods-with-
matlab-for-engineers-and-scientists-2nd-edition-steven-chapra-
solutions-manual/

Engineers Guide To MATLAB 3rd Edition Magrab Solutions


Manual

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

Programming with Mobile Applications Android iOS and


Windows Phone 7 1st Edition Duffy Solutions Manual

https://testbankfan.com/product/programming-with-mobile-
applications-android-ios-and-windows-phone-7-1st-edition-duffy-
solutions-manual/

Thermodynamics for Engineers 1st Edition Kroos


Solutions Manual

https://testbankfan.com/product/thermodynamics-for-engineers-1st-
edition-kroos-solutions-manual/
6. 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

139
© 2013 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
% ==== ========== =====================
% 07/03/11 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

140
© 2013 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
% ==== ========== =====================
% 07/03/11 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');

% Display the sorted result.


141
© 2013 Cengage Learning. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
fprintf('\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
2.0000
5.0000

142
© 2013 Cengage Learning. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
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 ==> d:\book\matlab\soln\Ex5.4\test_ssort1.m


On line 66 ==>

6.5 A set of functions to perform trigonometric operations in degrees are 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
% ==== ========== =====================
% 07/03/11 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
% ==== ========== =====================
% 07/03/11 S. J. Chapman Original code

% Check for a legal number of input arguments.


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

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

143
© 2013 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 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
% ==== ========== =====================
% 07/03/11 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
% ==== ========== =====================
% 07/03/11 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:
% Date Programmer Description of change
% ==== ========== =====================
% 07/03/11 S. J. Chapman Original code

% Check for a legal number of input arguments.


144
© 2013 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(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
% ==== ========== =====================
% 07/03/11 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
% ==== ========== =====================
% 07/03/11 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:

% Script file: test_functions.m


%
% Purpose:
% To perform a median filter on an input data set.
%
145
© 2013 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
% ==== ========== =====================
% 07/03/11 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
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
146
© 2013 Cengage Learning. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
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
% ==== ========== =====================
% 07/03/11 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)
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
147
© 2013 Cengage Learning. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% %
% 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
% ==== ========== =====================
% 07/03/11 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)

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

148
© 2013 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
% ==== ========== =====================
% 07/03/11 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 we can only up to the number of arguments in the calling sequence1. We will
design this function to support up to 6 vertices. The corresponding function is shown below:

function area = area_polygon(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5,
x6, y6)
%AREA_POLYGON Calculate the area of a polygon specified by its
vertices
% Function AREA_POLYGON calculates the area of a polygon specified by
% its vertices
%
% Calling sequence:
% area = area_polygon(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6,
y6)

% Define variables:
% ii -- Loop index
% n_vertices -- Number of vetices in polygon
% x1, y1 -- Location of vertex 1
% x2, y2 -- Location of vertex 2
% x3, y3 -- Location of vertex 3
% x4, y4 -- Location of vertex 4
% x5, y5 -- Location of vertex 5
% x6, y6 -- Location of vertex 6
% area -- Area of polygon

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 07/03/11 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.

1 Later we will learn about function varargin, which can support any number of arguments.
149
© 2013 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(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)


area =
100.00
>> area = area_polygon(10,0,8,8,2,10,-4,5)
area =
43.00

150
© 2013 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.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
% ==== ========== =====================
% 07/03/11 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 =
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
151
© 2013 Cengage Learning. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% 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
% ==== ========== =====================
% 07/03/11 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:
% 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
%
152
© 2013 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:
% data1 -- Array to sort
% data2 -- Copy of array to sort
% elapsed_time1 -- Elaosed time for ssort
% elapsed_time2 -- Elaosed 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 = 118.288
Sort time using sort = 0.013641

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.

Note that the sort time for the selection sort increases as the square of the number of values
sorted. This may make it impossible to do the calculation for 1,000,000 samples, as specified in
the original problem. This will be modified to 200,000 samples in subsequent printings.

% Script file: compare_sorts.m


%
% Purpose:
% To compare the sort function from Example 6.2 and the
% built-in MATLAB sort
%
% Record of revisions:

153
© 2013 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
% ==== ========== =====================
% 07/04/11 S. J. Chapman Original code
%
% Define variables:
% data1 -- Array to sort
% data2 -- Copy of array to sort
% elapsed_time1 -- Elaosed time for ssort
% elapsed_time2 -- Elaosed 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;

% Display the relative times


disp(['Sort time for ' int2str(nsamp) ' using ssort = '
num2str(elapsed_time1)]);
154
© 2013 Cengage Learning. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
disp(['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)]);

When this program is executed, the results are:

>> compare_sorts
Sort time using ssort = 118.288
Sort time using sort = 0.013641

The built-in sorting function is dramatically faster than the selection sort of Example 6.2.

>> compare_sorts
Sort time for 10000 using ssort = 1.2153
Sort time for 10000 using sort = 0.0013928
Sort time for 100000 using ssort = 137.3888
Sort time for 100000 using sort = 0.013531
Sort time for 200000 using ssort = 631.6224
Sort time for 200000 using sort = 0.026963

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:

155
© 2013 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
% 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/10 S. J. Chapman Original code
% 1. 07/04/11 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:

156
© 2013 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) -- 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)
% 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/10 S. J. Chapman Original code
% 1. 07/04/11 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

157
© 2013 Cengage Learning. All Rights Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% and 6.

% Define variables:
% result -- Resulting integer

% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 07/04/11 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
% ==== ========== =====================
% 07/04/11 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.

158
© 2013 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 lion roared, “Lambikin! Lambikin! I’ll eat you!”
But with a hop and a skip, a hump and a jump, Lambikin said,

“No, no,
To Granny’s house I go,
Where I shall fatter grow,
Then you can eat me so.”

The lion thought this wise and so let Lambikin go.


Away frisked Lambikin.
At last he reached his Granny’s house.
“Granny dear,” he cried, all out of breath, “I have said I would get
fat. I ought to keep my word. Please put me in the corn-bin at once.”
“You are a good Lambikin,” said his Granny.
And she put him into the corn-bin.
There the greedy little Lambikin stayed for seven days and seven
nights.
He ate, and ate, and ate, and he ate until he could hardly waddle.
“Come, Lambikin,” said his Granny, “you are fat enough. You
should go home now.”
“No, no,” said cunning little Lambikin, “that will never do. Some
animal would surely eat me on the way, I am so plump and tender.”
“Oh, dear! Oh, dear!” cried old Granny in a fright.
“Never fear, Granny dear,” said cunning Lambikin. “I’ll tell you what
to do. Just make me a little drumikin out of the skin of my little
brother who died. I can get into it and roll along nicely.”
So old Granny made Lambikin a drumikin out of the skin of his
dead brother.
And cunning Lambikin curled himself up into a round ball in the
drumikin.
And he rolled gayly away.
Soon he met the lion, who called out,

“Drumikin! Drumikin!
Have you seen Lambikin?”

Lambikin answered sweetly as he rolled along,

“Fallen into the fire, and so will you!


On, little Drumikin! Tum-pa, tum-too!”

“Too bad, too bad,” sighed the lion, as he thought of the sweet, fat
morsel of a Lambikin.
So away rolled Lambikin, laughing gayly to himself and sweetly
singing,

“Tum-pa, tum-too;
Tum-pa, tum-too!”

Soon he met the bear, who called out,

“Drumikin! Drumikin!
Have you seen Lambikin?”

Lambikin answered sweetly as he rolled along,

“Fallen into the fire, and so will you!


On, little Drumikin! Tum-pa, tum-too!”

“Too bad, too bad,” sighed the bear, as he thought of the sweet, fat
morsel of a Lambikin.
So away rolled Lambikin, laughing gayly to himself and sweetly
singing,

“Tum-pa, tum-too;
Tum-pa, tum-too!”
Soon he met the wolf, who called out,

“Drumikin! Drumikin!
Have you seen Lambikin?”

Lambikin answered sweetly as he rolled along,

“Fallen into the fire, and so will you!


On, little Drumikin! Tum-pa, tum-too!”

“Oh, ho, little Lambikin, curled up snug in your little drumikin,” said
the wolf, “you can’t fool me. I know your voice. So you have become
too fat to hop and to skip, to hump and to jump. You can only roll
along like a ball.”
And the wolf’s mouth watered as he thought of the sweet, fat
morsel of a Lambikin.
Little Lambikin’s heart went pit-a-pat, but he cried out gayly,

“Hark, hark! Hear the dogs bark!


Faster, roll faster, my little Drumikin!”

The wolf was frightened and stopped to listen for the dogs.
And away rolled cunning Lambikin faster and faster, laughing to
himself and sweetly singing,

“Tum-pa, tum-too;
Tum-pa, tum-too!”
THE ANT AND THE MOUSE

(h oney) (w ish) (c arry)


m oney f ish m arry

(th is) (r ob) (r each)


m iss c ob p each

pieces lost roost er


sharp buy hur ried

There was once an ant.


While sweeping her house one day, this ant found three pieces of
money.
“What shall I buy?” said she.
“Shall I buy fish?”
“No, fish is full of bones. I can’t eat bones. I’ll not buy fish.”
“Shall I buy bread?”
“No, bread has crust. I can’t eat crust. I’ll not buy bread.”
“Shall I buy peaches?”
“No, peaches have stones. I can’t eat stones. I’ll not buy peaches.”
“Shall I buy corn?”
“No, corn grows on a cob. I can’t eat cobs. I’ll not buy corn.”
“Shall I buy apples?”
“No, apples have seeds. I can’t eat seeds I’ll not buy apples.”
“Shall I buy a ribbon?”
“Yes, that’s just what I want. I will buy a ribbon.”
And away ran Miss Ant to the store and bought her a bright red
ribbon.
She tied the ribbon about her neck and sat in her window.
An ox came along and said, “How pretty you are, Miss Ant! Will
you marry me?”
“Sing,” said the ant, “so I may hear your voice.”
The ox was very proud of his voice and he
bellowed with all his might.
“No, no,” cried the ant, “I’ll not marry you,
Mr. Ox. Your bellow frightens me. Go away.”
Soon a lion came that way and said, “How
pretty you are, Miss Ant! Will you marry me?”
“Sing,” said the ant,
“so I may hear your
voice.”
The lion was proud
of his voice and he
roared with all his
might.
“No, no,” cried the ant, “I’ll not marry you,
Mr. Lion. Your loud roar frightens me. It
shakes the very hills. Go away.”
The lion had not been gone long when a
proud rooster came strutting along that way.
“How pretty you are, Miss Ant! Will you marry me?” said the
rooster.
“Sing,” said the ant, “so I may hear your voice.”
The rooster was very proud of his shrill voice and he crowed with
all his might.
“No, no,” cried the ant, “I’ll not marry you, Mr. Rooster. Your shrill
crow frightens me. Go away.”
The rooster was hardly out of sight when a
big dog came trotting that way.
“How pretty you are, Miss Ant! Will you
marry me?” said the dog.
“Sing,” said the ant, “so I may hear your
voice.”
The dog was very
proud of his voice and
he barked with all his
might.
“No, no,” cried the ant, “I’ll not marry you,
Mr. Dog. Your sharp bark frightens me. Go
away.”
After a time a wee little mouse came
frisking that way.
“How pretty you are, Miss Ant! Will you
marry me?” said the mouse.
“Sing,” said the ant, “so I may hear your
voice.”
Now the wee little mouse was not at all
proud of his voice. But he squeaked as
sweetly as he could, “Wee, wee, wee!”
“Yes, yes,” cried the ant, “I’ll marry you, dear Mouse. Your sweet
little voice pleases me. Come right in.”
In scampered the mouse.
The ant gave him two pieces of money, for she had spent only one
for her ribbon.
He hurried away to the store, and came quickly back bringing
apples and bread.
Mrs. Ant Mouse now sat down to a feast.
Mr. Mouse ate the crusts and the seeds, so nothing was lost.
Songs of Life
THE BROOK

(fl ies) branch es (l ove)


sk ies riv er ab ove
Down from the hillside,
Sparkling and bright,
Rushes the little brook,
In the sunlight.

On through the meadow,


Where the flowers hide,
With skies bright above it,
Now its waters glide.

Tall trees beside the brook,


Their branches o’er it throw,
As through the quiet woodland,
The sparkling waters flow.

So it hurries down the hillside,


And across the meadow sweet,
And through the shady woodland,
Till the river it shall meet.
THE LITTLE BROOK

(l ift) (gr ass) (spl ash)


sw iftly p ass d ash
fl ash
(th is) mur murs ash
wh is per talk

See the little brook rushing down the steep hillside!


How it hurries!
How it leaps over the falls!
Hear it dash and splash among the rocks!
See its waters flash and sparkle in the sun!
“Stop, stop, little brook! Wait, I want to talk with you.”
“No, no, I must hurry on. I have a long way to go.”
“I will go with you, then. I will run along your banks. Please do not
hurry so. I can hardly keep up with you.”
Now we come to the wide meadow.
Here the little brook flows more slowly and quietly.
But it never stops.
It must flow ever on and on.
Bright flowers are hiding along its banks.
They peep out from the grass.
They look into the clear flowing water.
“Stay, little brook, play with us,” they whisper.
“Why do you always hurry so? Are you not weary?”
“No, no, I am never weary, never tired,” murmurs the brook.
“I never stop to play.
It is play for me to rush swiftly down the steep hill.
It is fun to flow gently across the meadow.
I like to see you peeping over my banks as I pass.
But I cannot stop.
I must hurry on to meet the river.
Good-by, sweet flowers, good-by.”
Now the brook glides into the woodland.
Here the sad willows droop over the gliding waters.
High above them tower the oak, the ash, and the pine trees.
“Do not hurry, little brook,” whisper their leaves.
“Are you not tired?
You have come a long way.
Here the bright sun never comes.
Stay with us, and we will shade you.
Rest a while under our spreading branches.
In the meadow the burning sun is so hot.
But here it is cool.
Why can you not stay with us?
Why must you always hurry on?”
“Because I have to meet the river.
I love your wide spreading branches.
I love the gentle murmur of your green leaves.
I love your cool shade.
You are very kind to me.
But I cannot stay with you.
The great river needs me.
I shall have to hurry on.
Good-by, noble trees.
Good-by, drooping willows.”
So the never resting brook rushes, and glides and flows on
forever.

CALLING THE VIOLET

mos sy don’t
Dear little Violet,
Don’t be afraid!
Lift your blue eyes
From the rock’s mossy shade.
All the birds call for you
Out of the sky;
May is here waiting,
And here, too, am I.

Come, pretty Violet,


Winter’s away;
Come, for without you
May isn’t May.
Down through the sunshine
Wings flutter and fly;
Quick, little Violet,
Open your eye!

—Lucy Larcom.

THE WIND

(m oss y) (w hen) (c oats)


t oss es w hen ce g oats

height (sh all) trav erse


up ward v all ey whith er
Which way does the wind blow,
And where does he go?
He rides o’er the water
And over the snow;
O’er wood and o’er valley,
And over the height—
Where goats cannot traverse
He taketh his flight.

He rages and tosses,


And bare is the tree,
As when you look upward
You plainly can see;
But from whence he comes,
Or whither he goes,
There is no one can tell you,
There is no one who knows.

—Mary Lamb.

THE WIND

nei ther (h ow)


trem bling b ow
Who has seen the wind?
Neither I nor you;
But when the leaves hang trembling,
The Wind is passing through.

Who has seen the wind?


Neither you nor I;
But when the trees bow down their heads,
The Wind is passing by.

THE WIND

dif fer ent la dies


young skirts
I saw you toss the kites on high
And blow the birds about the sky;
And all around I heard you pass,
Like ladies’ skirts across the grass—
O wind, a-blowing all day long,
O wind, that sings so loud a song!

I saw the different things you did,


But always you yourself you hid.
I felt you push, I heard you call,
I could not see yourself at all—
O wind, a-blowing all day long,
O wind, that sings so loud a song!

O you that are so strong and cold,


O blower, are you young or old?
Are you a beast of field and tree,
Or just a stronger child than me?
O wind, a-blowing all day long,
O wind, that sings so loud a song!

—R. L. Stevenson

THE LEAF’S JOURNEY

You might also like