You are on page 1of 49

MATLAB Programming for Engineers

5th Edition Chapman Solutions Manual


Visit to download the full and correct content document: https://testbankdeal.com/dow
nload/matlab-programming-for-engineers-5th-edition-chapman-solutions-manual/
7. Advanced Features of User-Defined Functions
7.1 Function random1 produces samples from a uniform random distribution on the range [-1,1). Note that
function random0 is a local function (or subfunction) of this function, since it appears in the same file
below the definition of random1. Function random0 is only accessible from function random1, not
from external functions. This is different from the behavior of the function random0 included with the
function random1 written in Exercise 6.29.

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/10/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;

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

185
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Define variables:
% ii -- Index variable
% ISEED -- Random number seed (global)
% jj -- Index variable
% m -- Number of columns
% msg -- Error message
% n -- Number of rows
% ran -- Output array
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 02/04/14 S. J. Chapman Original code
% 1. 04/05/15 S. J. Chapman Modified for 0 arguments

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

% 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

186
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
7.2 Function randomn produces samples from a uniform random distribution on the range [low,high). If
low and high are not supplied, they default to 0 and 1 respectively. Note that function random0 is
placed in a folder named private below the folder containing randomn. Function random0 is only
accessible from function in the parent directory, not from other functions. A listing of the directory is
shown below:

C:\Data\book\matlab\5e\soln\Ex7.2>dir /s
Volume in drive C is SYSTEM
Volume Serial Number is 9084-C7B1

Directory of C:\Data\book\matlab\5e\soln\Ex7.2

02/05/2015 01:16 PM <DIR> .


02/05/2015 01:16 PM <DIR> ..
02/05/2015 01:16 PM <DIR> private
25/09/2011 11:36 AM 1,297 randomn.m
1 File(s) 1,297 bytes

Directory of C:\Data\book\matlab\5e\soln\Ex7.2\private

02/05/2015 01:16 PM <DIR> .


02/05/2015 01:16 PM <DIR> ..
19/05/2015 06:01 PM 1,473 random0.m
1 File(s) 1,473 bytes

Total Files Listed:


2 File(s) 2,770 bytes
5 Dir(s) 79,965,483,008 bytes free

C:\Data\book\matlab\5e\soln\Ex7.2>

Function randomn is shown below:

function ran = randomn(n,m,low,high)


%RANDOMN Generate uniform random numbers in [low,high)
% Function RANDOM1 generates an array of uniform
% random numbers in the range [low,high), where low
% and high are optional parameters supplied by the user.
% If not supplied, low and high default to 0 and 1,
% respectively. The usage is:
%
% random1(n) -- Generate an n x n array
% random1(n,m) -- Generate an n x m array

% Define variables:
% high -- Upper end of range
% low -- Lower end of range
% m -- Number of columns
% n -- Number of rows
% ran -- Output array

% Record of revisions:
% Date Programmer Description of change
187
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% ==== ========== =====================
% 04/10/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


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

% If arguments are missing, supply the default values.


if nargin < 2
m = n;
low = 0;
high = 1;
elseif nargin < 3
low = 0;
high = 1;
elseif nargin < 4
high = 1;
end

% Check that low < high


if low >= high
error('Lower limit must be less than upper limit!');
end

% Initialize the output array


ran = (high - low) * random0(n,m) + low;

The following function appears in a directory name private below the directory containing function
randomn:

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)
% 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
188
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% 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);

% 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

When this function is used to generate a 4 x 4 array of random numbers between 3 and 4 the results are: :

>> randomn(4,4,3,4)
ans =
3.7858 3.0238 3.4879 3.5630
3.5319 3.0040 3.3435 3.0988
3.4300 3.5385 3.0946 3.6670
3.1507 3.1958 3.6362 3.9179

7.3 A single function hyperbolic that calculates the hyperbolic sine, cosine, and tangent functions is shown
below. Note that sinh, cosh, and tanh are subfunctions here.

function result = hyperbolic(fun,x)


% HYPERBOLIC Calculate the hyperbolic sine of x
% Function HYPERBOLIC calculates the value of a hyperbolic
% sin, cos, or tan, depending on its its input parameter.

% Define variables:
% fun -- Function to evaluate
189
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% x -- Input value
% result -- Result of calculation

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

% Check for a legal number of input arguments.


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

% Calculate function
switch (fun)
case 'sinh',
result = sinh(x);
case 'cosh',
result = cosh(x);
case 'tanh',
result = tanh(x);
otherwise,
msg = ['Invalid input function: ' fun];
error(msg);
end

function result = sinh1(x)


%SINH1 Calculate the hyperbolic sine of x
% Function SINH1 calculates the hyperbolic sine of
% its input parameter.

% Define variables:
% x -- input value
% result -- Result of calculation

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

% Check for a legal number of input arguments.


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

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

function result = cosh1(x)


%COSH1 Calculate the hyperbolic cosine of x
% Function COSH1 calculates the hyperbolic cosine of
% its input parameter.

190
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Define variables:
% x -- input value
% result -- Result of calculation

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

% Check for a legal number of input arguments.


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

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

function result = tanh1(x)


%COSH1 Calculate the hyperbolic tangent of x
% Function TANH1 calculates the hyperbolic tangent
% of its input parameter.

% Define variables:
% x -- input value
% result -- Result of calculation

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

% Check for a legal number of input arguments.


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

% Calculate value. Note that we are using the


% array division "./" so that we get the correct
% answer in case an arry input argument is passed
% to this function.
result = (exp(x) - exp(-x)) ./ (exp(x) + exp(-x));

7.4 A program to create the three specified anonymous functions, and then to plot h ( f ( x ) , g ( x) ) over the
range −10 ≤ x ≤ 10 is shown below:
% Script file: test_anonymous.m
%
% Purpose:
% To create three anonymous functions, and then create a
% plot using them.
%
191
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/10/15 S. J. Chapman Original code
%
% Define variables:
% f -- Function handle
% g -- Function handle
% h -- Function handle
% x -- Input data samples

% Create anonymous functions


f = @ (x) 10 * cos(x);
g = @ (x) 5 * sin(x);
h = @ (a,b) sqrt(a.^2 + b.^2);

% Plot the functiion h(f(x),g(x))


x = -10:0.1:10;
plot(x,h(f(x),g(x)));

When this program is executed, the results are:

7.5 The commands to plot the function f ( x) = 1/ x over the range 0.1 ≤ x ≤ 10.0 using function fplot
are shown below:

fplot(@(x) 1/sqrt(x), [0.1 10]);


title('Plot of f(x) = 1 / sqrt(x)');

192
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
xlabel('\bfx');
ylabel('\bff(x)');
grid on;

When these commands are executed, the results are:

7.6 A script file to find the minimum of the function y ( x ) = x 4 − 3 x 2 + 2 x over the interval [0.5 1.5] using
function fminbnd is shown below:

% Script file: test_fminbnd.m


%
% Purpose:
% To test function fminbnd using an anonymous function
% as an input fucntion.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/10/15 S. J. Chapman Original code
%
% Define variables:
% minloc -- Location of minimum
% minval -- Value at minimum
% y -- Function handle
% x -- Input data samples

% Create anonymous function


y = @ (x) x.^4 - 3*x.^2 + 2*x;

193
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Find the minimum of the function in the range
% 0.5 <= x <= 1.5.
[minloc,minval] = fminbnd(y,0.5,1.5);
disp(['The minimum is at location ' num2str(minloc)]);

% Plot the function


z = linspace(-4,4,100);
plot(z,y(z));
grid on;
xlabel('\bfx');
ylabel('\bfy');
grid on;

When this program is executed, the results are:

>> test_fminbnd
The minimum is at location 0.99999

7.7 A script file to find the minimum of the function y ( x ) = x 4 − 3 x 2 + 2 x over the interval [0.5 1.5] using
function fminbnd is shown below:

% Script file: test_fminbnd.m


%
% Purpose:
% To test function fminbnd using an anonymous function
% as an input fucntion.
%
% Record of revisions:
194
© 2016 Cengage Learning®. 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/10/15 S. J. Chapman Original code
%
% Define variables:
% minloc -- Location of minimum
% minval -- Value at minimum
% y -- Function handle
% x -- Input data samples

% Create anonymous function


y = @ (x) x.^4 - 3*x.^2 + 2*x;

% Find the minimum of the function in the range


% -2 < x < 2.
[minloc,minval] = fminbnd(y,-2.0,2.0);
disp(['The minimum in the range (-2,2) is at location
' num2str(minloc)]);

% Find the minimum of the function in the range


% -1.5 < x < 0.5.
[minloc,minval] = fminbnd(y,-1.5,0.5);
disp(['The minimum in the range (-1.5,0.5) is at location
' num2str(minloc)]);

% Plot the function


z = linspace(-2.5,2.5,100);
plot(z,y(z));
grid on;
xlabel('\bfx');
ylabel('\bfy');
grid on;

When this program is executed, the results are:

>> test_fminbnd
The minimum in the range (-2,2) is at location -1.366
The minimum in the range (-1.5,0.5) is at location -1.366

195
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
7.8 A script file to create a histogram of samples from a random normal distribution is shown below:

% Script file: test_randn.m


%
% Purpose:
% To create a histogram of 100,000 samples from a random
% normal distribution.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/10/15 S. J. Chapman Original code
%
% Define variables:
% dist -- Samples

% Get 100,000 values


dist = randn(1,100000);

% Create histogram
hist(dist,21);
title('\bfHistogram of random values');
xlabel('\bfValue');
ylabel('\bfCount');

196
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
When this program is executed, the results are:

>> test_randn

7.9 A Rose Plot is a circular histogram, where the angle data theta is divided into the specified number of
bins, and the count of values in each bin is accumulated. A script file to create a rose plot of samples from
a random normal distribution is shown below:

% Script file: test_rose.m


%
% Purpose:
% To create a rose plot of 100,000 samples from a random
% normal distribution.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/10/15 S. J. Chapman Original code
%
% Define variables:
% dist -- Samples

% Get 100,000 values


dist = randn(1,100000);

% Create histogram
rose(dist,21);
title('\bfRose Plot of random values');
197
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
xlabel('\bfValue');
ylabel('\bfCount');

When this program is executed, the results are:

>> test_rose

7.10 A function that finds the maximum and minimum values of a user-supplied function over a specified
interval is given below:

function [xmin,min_value,xmax,max_value] = ...


extremes(first_value,last_value,num_steps,func)
%EXTREMES Locate the extreme values of a function on an interval
% Function EXTREMES searches a user-supplied function over
% a user-suppled interval, and returns the minimum and maximum
% values found, as well as their locations.
%
% The calling sequence is:
% [xmin,min_value,xmax,max_value] = ...
% extremes(first_value,last_value,num_steps,func);
%
% where
% first_value = the start of the interval to search
% last_value = the end of the interval to search
% num_steps = the number of steps to use in search
% func = the function to evaluate
%
% The output values are:

198
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% xmin = location of smallest value found
% min_value = smallest value found
% xman = location of largest value found
% max_value = largest value found

% Define variables:
% dx -- Step size
% x -- Input values to evaluate fun at
% y -- Function output

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

% Check for a legal number of input arguments.


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

% Create array of values to evaluate the function at


dx = (last_value - first_value) / (num_steps - 1);
x = first_value:dx:last_value;

% Evaluate function
y = feval(func,x);

% Find maximum and minimum in y, and the locations in


% the array where they occurred.
[max_value, ymax] = max(y);
[min_value, ymin] = min(y);

% Get the x values at the locations of the maximum and


% minimum values.
xmax = x(ymax);
xmin = x(ymin);

7.11 A test program that tests function extremes is shown below:

% Script file: test_extremes.m


%
% Purpose:
% To test function extremes.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/12/15 S. J. Chapman Original code
%
% Define variables:
% max_value -- Maximum value
% min_value -- Minimum value
% xmax -- Location of maximum value
% xmin -- Location of minimum value
199
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Call extremes
[xmin,min_value,xmax,max_value] = extremes(-1,3,201,'fun');

% Display results
fprintf('The maximum value is %.4f at %.2f\n',max_value,xmax);
fprintf('The minimum value is %.4f at %.2f\n',min_value,xmin);

The test function to evaluate is

function y = fun(x)
%FUN Function to test extremes

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

y = x.^3 - 5*x.^2 + 5*x +2;

When this program is run, the results are as shown below. The plot of the function below shows that the
program has correctly identified the extremes over the specified interval.

» test_extremes
The maximum value is 3.4163 at 0.62
The minimum value is -9.0000 at -1.00

200
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
7.12 The function fzero locates a zero in a function either near to a user-specified point or within a user-
specified range. If a range is used, then the sign of the function must be different at the beginning and end
of the range. This suggests a strategy for solving this problem—we will search along the function between
0 and 2 π at regular steps, and if the function changes sign between two steps, we will call fzero to
home in on the location of the root.

Note that we can determine whether the function has changed sign between two points by multiplying them
together and seeing the resulting sign. If the sign of the product is negative, then the sign must have
changed between those two points.

% Script file: find_zeros.m


%
% Purpose:
% To find the zeros of the function f(x) = (cos (x))^2 - 0.25
% between 0 and 2*PI.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/12/15 S. J. Chapman Original code
%
% Define variables:
% x -- Input values to examine
% y -- Value of the function at x
% zero_index -- Index into the zero array
% zero_loc -- Location of zeros

% Create function
hndl = @ (x) cos(x).^2 - 0.25;

% Evaluate the function at 50 points between 0 and 2*PI.


x = linspace(0,2*pi,50);
y = hndl(x);

% Check for a sign change


zero_loc = [];
zero_index = 0;
for ii = 1:length(x)-1
if y(ii)*y(ii+1) <= 0

% Find zeros
zero_index = zero_index + 1;
zero_loc(zero_index) = fzero(hndl,[x(ii) x(ii+1)]);

% Display results
disp(['There is a zero at at ' num2str(zero_loc(zero_index))]);

end
end

% Now plot the function to demonstrate that the zeros are correct
figure(1);
plot(x,y,'b-','LineWidth',2);
201
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
hold on;
plot(zero_loc,zeros(size(zero_loc)),'ro');
hold off;
title('\bfLocation of Function Zeros');
xlabel('\bfx');
ylabel('\bfy');
legend('Function','Zeros found by fzero');
grid on;

When this program is run, the results are as shown below. The plot of the function below shows that the
program has correctly identified the zeros over the specified interval.

>> find_zeros
There is a zero at at 1.0472
There is a zero at at 2.0944
There is a zero at at 4.1888
There is a zero at at 5.236

7.13 A program to evaluate and plot the function f ( x ) = tan 2 x + x − 2 between −2π and 2π in steps of
π /10 is shown below:
% Script file: eval_and_plot_fn.m
%
% Purpose:
% To find the zeros of the function f(x) = (cos (x))^2 - 0.25
% between 0 and 2*PI.
%
% Record of revisions:

202
© 2016 Cengage Learning®. 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/12/15 S. J. Chapman Original code
%
% Define variables:
% hndl -- Function handle
% x -- Input values to examine
% y -- Value of the function at x

% Create function handle


hndl = @ fun;

% Evaluate the function at 50 points between 0 and 2*PI.


x = linspace(0,2*pi,200);
y = feval(hndl,x);

% Now plot the function


figure(1);
plot(x,y,'b-','LineWidth',2);
title('\bfPlot of function');
xlabel('\bfx');
ylabel('\bfy');
grid on;

When this program is run, the results are as shown below. The plot is shown twice, once at full scale and
once with the maximum y axis value limited to 50, so that the details of the plot can be observed.

>> eval_and_plot_fn

203
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
7.14 A program to find potential targets in a radar’s range/Doppler space is shown below. This program finds
potential targets by looking for points that are higher than all of the neighboring points.

% Script file: find_radar_targets.m


%
% Purpose:
% This program detects potential targets in the range /
% velocity space.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/12/15 S. J. Chapman Original code
%
% Define variables:
% amp_levels -- Amplitude level of each bin
% noise_power -- Power level of peak noise
% nvals -- Number of samples in each bin

% Load the data


load rd_space.mat

% Calculate histogram
[nvals, amp_levels] = hist(amp(:), 31);

% Get location of peak

204
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
[max_val, max_loc] = max(nvals);

% Get the power level of that bin


noise_power = amp_levels(max_loc);

% Now look for targets. A potential target is a point that


% is higher than all of the points around it.
fprintf(' Range Vel Amp SNR\n');
for ii = 2:length(velocity)-1
for jj = 2:length(range)-1

% Is this point bigger than the surrounding ones?


if (amp(ii,jj) > amp(ii+1,jj)) && ...
(amp(ii,jj) > amp(ii-1,jj)) && ...
(amp(ii,jj) > amp(ii,jj+1)) && ...
(amp(ii,jj) > amp(ii,jj-1))

% Yes. This is a potential target.


snr = amp(ii,jj) - noise_power;

% Tell user
fprintf('%7.1f %6.1f %6.1f %6.1f\n', ...
range(jj), velocity(ii), amp(ii,jj), snr);
end
end
end

When this program is executed, the results are:

>> find_radar_targets
Range Vel Amp SNR
-161.9 1.7 -100.9 4.1
-89.9 1.7 -98.8 6.1
125.9 1.7 -95.2 9.7
-143.9 2.5 -107.1 -2.2
-54.0 2.5 -96.8 8.1
-125.9 3.3 -106.3 -1.4
-89.9 4.1 -98.0 6.9
0.0 4.1 -72.3 32.6
125.9 4.1 -102.0 2.9
89.9 5.0 -101.9 3.0
143.9 5.0 -101.3 3.6
-125.9 5.8 -98.6 6.3
107.9 5.8 -104.7 0.2
-72.0 6.6 -96.5 8.4
0.0 6.6 -73.2 31.8
143.9 6.6 -101.3 3.6
-107.9 7.5 -100.7 4.2
-54.0 7.5 -97.7 7.2
107.9 7.5 -102.7 2.2
125.9 8.3 -102.3 2.6
0.0 9.1 -73.9 31.0
205
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
72.0 9.1 -100.5 4.5
107.9 9.1 -102.2 2.8
-161.9 10.8 -99.3 5.6
0.0 10.8 -74.3 30.6
-72.0 11.6 -102.0 2.9
89.9 11.6 -99.5 5.4
0.0 12.4 -74.6 30.3
107.9 12.4 -102.4 2.5
143.9 12.4 -99.2 5.7
-125.9 13.3 -98.7 6.2
89.9 14.1 -106.7 -1.8
-72.0 14.9 -99.7 5.2
0.0 14.9 -74.9 30.0
-125.9 15.8 -97.9 7.0
-89.9 15.8 -98.0 6.9
143.9 15.8 -101.8 3.1
-143.9 17.4 -99.2 5.7
125.9 17.4 -97.4 7.5
143.9 18.3 -99.3 5.7
107.9 19.1 -102.9 2.0
-125.9 19.9 -101.3 3.6
0.0 19.9 -75.2 29.7
-72.0 20.8 -100.5 4.4
125.9 20.8 -95.7 9.2
-54.0 21.6 -99.8 5.2
-161.9 22.4 -99.9 5.1
-125.9 22.4 -103.1 1.8
0.0 22.4 -75.4 29.5
-107.9 23.2 -103.2 1.7
107.9 23.2 -103.8 1.1
143.9 23.2 -97.7 7.2
-125.9 24.1 -102.5 2.4
0.0 24.1 -75.4 29.5
-72.0 24.9 -103.0 1.9
89.9 24.9 -111.1 -6.2
-161.9 25.7 -99.1 5.8
-107.9 25.7 -96.7 8.3
-54.0 25.7 -97.7 7.2
0.0 25.7 -75.7 29.2
143.9 25.7 -96.5 8.5
107.9 26.6 -99.8 5.1
-161.9 28.2 -98.4 6.5
-125.9 28.2 -100.1 4.8
-72.0 28.2 -105.1 -0.1
0.0 28.2 -75.5 29.4
72.0 28.2 -95.9 9.0
-89.9 29.0 -104.4 0.5
107.9 29.0 -102.0 2.9
-125.9 29.9 -101.4 3.5
0.0 29.9 -75.1 29.8
-72.0 30.7 -96.7 8.2
-143.9 31.5 -100.6 4.4
0.0 31.5 -75.0 29.9
206
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
-125.9 32.4 -102.7 2.2
125.9 32.4 -103.4 1.6
-143.9 33.2 -102.0 3.0
-107.9 34.0 -105.1 -0.2
-72.0 34.0 -101.7 3.3
89.9 34.0 -103.3 1.6
-125.9 34.9 -103.8 1.1
0.0 34.9 -74.8 30.1
125.9 34.9 -100.0 4.9
107.9 35.7 -98.0 6.9
-161.9 36.5 -99.5 5.4
-89.9 36.5 -103.8 1.2
143.9 37.4 -104.3 0.6
-143.9 38.2 -103.7 1.2
-107.9 38.2 -102.0 2.9
-72.0 38.2 -102.4 2.5
0.0 38.2 -74.1 30.8
-161.9 39.0 -98.7 6.2
-125.9 39.8 -103.1 1.8
-54.0 39.8 -98.2 6.7
125.9 40.7 -100.4 4.6
-125.9 42.3 -101.3 3.7
-89.9 42.3 -96.7 8.3
143.9 42.3 -98.2 6.8
107.9 43.2 -103.2 1.8
143.9 44.0 -98.6 6.4
-125.9 44.8 -95.8 9.1
125.9 45.6 -97.5 7.5
-107.9 46.5 -96.4 8.5
-72.0 46.5 -100.9 4.1
-54.0 47.3 -97.4 7.5
107.9 47.3 -102.8 2.1
-143.9 48.1 -100.1 4.8
-107.9 48.1 -99.2 5.7
-161.9 49.0 -98.6 6.3
-125.9 49.0 -98.5 6.4
125.9 49.0 -100.0 4.9
18.0 49.8 -65.4 39.5
-161.9 52.3 -53.5 51.4
-89.9 52.3 -51.7 53.2
18.0 52.3 -10.0 94.9
107.9 52.3 -50.8 54.1
-143.9 55.6 -98.9 6.0
-72.0 56.4 -105.0 -0.0
-89.9 57.3 -98.4 6.5
107.9 57.3 -99.3 5.6
143.9 57.3 -102.7 2.3
-125.9 58.1 -97.9 7.0
89.9 58.1 -104.3 0.6
125.9 58.9 -101.7 3.2
-161.9 59.8 -100.6 4.3
89.9 60.6 -99.8 5.1
143.9 60.6 -100.5 4.4
207
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
-125.9 61.4 -98.6 6.3
-161.9 62.3 -100.1 4.8
89.9 62.3 -102.6 2.4
143.9 62.3 -100.2 4.8
-89.9 63.1 -101.5 3.4
107.9 63.1 -100.8 4.1
-161.9 63.9 -100.0 4.9
-125.9 63.9 -102.3 2.6
0.0 63.9 -62.6 42.4
89.9 64.7 -97.1 7.8
125.9 64.7 -102.8 2.1
0.0 67.2 -21.0 83.9
107.9 69.7 -99.0 6.0
-143.9 70.5 -100.2 4.7
125.9 70.5 -98.9 6.0
-125.9 71.4 -99.2 5.7
-72.0 71.4 -110.0 -5.1
0.0 71.4 -62.5 42.4
89.9 71.4 -101.5 3.4
-107.9 72.2 -104.7 0.2
143.9 72.2 -105.2 -0.3
-161.9 73.0 -101.3 3.7
-89.9 73.0 -102.9 2.0
125.9 73.0 -97.3 7.6
-125.9 73.9 -101.1 3.8
-72.0 73.9 -101.3 3.7
-161.9 74.7 -102.1 2.8
-107.9 74.7 -100.0 4.9
-143.9 75.5 -102.3 2.6
107.9 75.5 -100.5 4.4
-72.0 76.4 -100.3 4.6
-161.9 77.2 -103.7 1.2
-107.9 77.2 -100.7 4.3
125.9 77.2 -103.8 1.1
-125.9 78.0 -102.0 3.0
143.9 78.0 -103.3 1.6
89.9 78.8 -102.7 2.2
-143.9 79.7 -98.0 6.9
-89.9 79.7 -100.4 4.5
125.9 79.7 -96.3 8.6
-107.9 80.5 -100.1 4.8
-54.0 80.5 -102.5 2.4
-125.9 82.2 -98.6 6.3
-89.9 82.2 -99.2 5.8
107.9 82.2 -100.3 4.6
143.9 82.2 -99.4 5.5

Which target has the highest signal to noise ratio? What is the relative range and velocity of that target?

208
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
7.15 A function to calculate the derivative of a sampled function is shown below:

function der = derivative(vector,dx,nsamp)


%DERIVATIVE Take the derivative of a function stored as a vector
% Function DERIVATIVE takes the derivative of a functions stored
% as an input vector if nsamp samples with a spacing of dx between
% samples.
%
% The calling sequence is:
% der = derivative(vector,dx,nsamp);
%
% where
% vector = the input function
% dx = step size between elements of the input vector
% nsamp = the number of elements in the vector

% Define variables:
% dx -- Step size
% x -- Input values to evaluate fun at
% y -- Function output

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

% Check for a legal number of input arguments.


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

% Check for a positive step size


if dx <= 0
error('dx must be positive!');
end

% Create array of values to evaluate the function at


der = diff(vector(1:nsamp)/dx);

A program to test function derivative is shown below:

% Script file: test_derivative.m


%
% Purpose:
% To test the function derivative.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/12/15 S. J. Chapman Original code
%
% Define variables:
% cosx -- cos(x)
% der -- derivative of sin(x)
209
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% dx -- Step size
% sinx -- sin(x)
% x -- Input values

% Calculate sin(x)
dx = 0.05;
x = 0:dx:99*dx;
sinx = sin(x);

% Calculate cos(x)
cosx = cos(x);

% Calculate derivative of sin(x)


der = derivative(sinx,dx,length(sinx));

% Plot sin(x), cos(x), and the derivative


figure(1);
plot(x,sinx,'b--','LineWidth',2);
hold on;
plot(x,cosx,'k-','LineWidth',2);

% Since the derivative is 1 shorter than the


% other vectors, it must be plotted versus
% a shorter x vector.
x1 = x(1:length(x)-1);
plot(x1,der,'r:','LineWidth',2);
legend ('sin(x)','cos(x)','derivative');
title('\bfPlot of sin(x), cos(x), and the derivative of sin(x)');
xlabel('\bf\itx');
ylabel('\bfValue');
hold off;

210
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
The resulting plot is shown below. The derivative of sin(x) as calculated by the function is indeed very
close to cos(x).

7.16 A program that explores the effect of noise on a derivative is shown below:

% Script file: test_derivative2.m


%
% Purpose:
% To test the function derivative in the presence of noise.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/12/15 S. J. Chapman Original code
%
% Define variables:
% der -- derivative of sin(x)
% dern -- derivative of sin(x) plus noise
% dx -- Step size
% sinx -- sin(x)
% sinxn -- sin(x) plus noise
% x -- Input values

% Calculate sin(x)
dx = 0.05;
x = 0:dx:99*dx;
sinx = sin(x);

211
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Calculate sin(x) plus noise
noise = 0.04 * random0(1,length(sinx)) - 0.02;
sinxn = sinx + noise;

% Calculate derivative of sin(x)


der = derivative(sinx,dx,length(sinx));

% Calculate derivative of sin(x) plus noise


dern = derivative(sinxn,dx,length(sinx));

% Plot sin(x) and the derivative


figure(1);
plot(x,sinx,'b-','LineWidth',2);
hold on;
plot(x,sinxn,'k--','LineWidth',2);

% Since the derivative is 1 shorter than the


% other vectors, it must be plotted versus
% a shorter x vector.
x1 = x(1:length(x)-1);
plot(x1,der,'m-','LineWidth',2);
plot(x1,dern,'r--','LineWidth',2);
legend ('sin(x)','sin(x)+noise','d/dt sin(x)', 'd/dt sin(x)+noise');
title('\bfEffect of noise on a derivative');
xlabel('\bf\itx');
ylabel('\bfValue');
hold off;

212
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
The resulting plot is shown below. The noise in the input signal is greatly amplified by the process of
taking the derivative.

7.17 A program that explores the effect of noise on a derivative is shown below:

% Script file: find_roots.m


%
% Purpose:
% To find the roots of the function y(x) = 2 * exp(-0.5*x) - 0.2
% between 0 and 7.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/13/15 S. J. Chapman Original code
%
% Define variables:
% root_index -- Index into the root array
% root_loc -- Location of roots
% x -- Input values to examine
% y -- Value of the function at x

% Create anonymous functions


f = @ (x) 2 * exp(-0.5*x) - 0.2;

% Evaluate the function at 50 points between 0 and 7.


x = linspace(0,7,50);
y = f(x);
213
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Check for a sign change
root_loc = [];
root_index = 0;
for ii = 1:length(x)-1
if y(ii)*y(ii+1) <= 0

% Find roots
root_index = root_index + 1;
root_loc(root_index) = fzero(f,[x(ii) x(ii+1)]);

% Display results
disp(['There is a root at at ' num2str(root_loc(root_index))]);

end
end

% Now plot the function to demonstrate that the roots are correct
figure(1);
plot(x,y,'b-','LineWidth',2);
hold on;
plot(root_loc,zeros(size(root_loc)),'ro');
hold off;
title('\bfLocation of Function roots');
xlabel('\bfx');
ylabel('\bfy');
legend('Function','roots found by froot');
grid on;

When this program is executed, the result is.

>> find_roots
There is a root at at 4.6052

214
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
The resulting plot is shown below.

7.18 A corrected version of function fact is shown below:

function result = fact(n)


%FACT Calculate the factorial function
% Function FACT calcualates the factorial function
% by recursively calling itself.

% Define variables:
% n -- Non-negative integer input
% result -- Result of calculation
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 07/07/14 S. J. Chapman Original code
% 1. 04/13/15 S. J. Chapman CHeck for invalid input

% Check for a legal number of input arguments.


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

% Make sure n is a non-negative integer


if (round(n) ~= n) || (n < 0)
error('n must be a non-negative integer');
else
% Calculate value.
215
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
if n >= 1
result = n * fact(n-1);
else
result = 1;
end
end

When this program is executed, the result is.

>> fact(5)
ans =
120
>> fact(-4)
??? Error using ==> fact at 22
n must be a non-negative integer

>> fact(5.5)
??? Error using ==> fact at 22
n must be a non-negative integer

7.19 A function to calculate the nth Fibonacci number recursively is shown below.

function fn = fibonacci(n)
%FIBONACCI evaluates the nth Fibonacci number
% Function FIBONACCI evaluates the nth Fibonacci number
% recursively, where n is >= 0.
%

% Define variables:
% fn -- Fibonacci number
% n -- The item in the sequence to calculate
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/13/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


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

% Make sure n is a non-negative integer


if (round(n) ~= n) || (n < 0)
error('n must be a non-negative integer');
else
% Calculate value.
if n == 0
fn = 0;
elseif n == 1
fn = 1;
else
fn = fibonacci(n-1) + fibonacci(n-2);
end
216
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
end

When this program is executed, the results are as shown below. Note that the error checks are working
properly, and the main calculations are also correct.

>> fibonacci(-1)
??? Error using ==> fibonacci at 21
n must be a non-negative integer

>> fibonacci(1)
ans =
1
>> fibonacci(5)
ans =
5
>> fibonacci(10)
ans =
55

7.20 A function that calculates the probability that two or more people from a group of n will have the same
birthday is shown below. This function calculates the probability by taking 100,000 random samples of n
people, and seeing if any two or more have the same birthday. In general, the resulting probabilities should
be accurate to within 1%. (Note: If you have a slow computer, you can reduce the number of trials that the
function is performing to improve execution time.)

function prob = birthday(n)


%BIRTHDAY Calculate the prob of 2 or more of n people having
% the same birthday.
% This function calculates the probability of two or more of
% n people having the same birthday, where "n" is a calling
% parameter.
%
% The calling sequence is:
% prob = birthday(n);
%
% where
% prob = Probability of 2 or more people having the same birthday
% n = Number of people in group

% Define variables:
% birthdays -- Array of birthdays
% ii -- Loop index
% jj -- Loop index
% n_matches -- Number of matches that have occurred
% n_trials -- The number of trials to perform
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/13/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


msg = nargchk(1,1,nargin);
217
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
error(msg);

% Check to make sure that there are at least 2 people


if n < 2
error('There must be at least two people in the group!');
end

% Set the number of trials to try


n_trials = 100000;

% Reset the number of matches


n_matches = 0;

% To determine this probability, we will generate an


% array of "n" random birthdays, and check to see if
% two or more are the same. We will repeat this process
% "n_trials" times, and calculate the probability from
% the result
for ii = 1:n_trials

% Generate a list of "n" random birthdays. Note that


% there is an equal probability of each number between
% 1 and 365.
birthdays = floor( 365 * rand(1,n)) + 1;

% Now check for matches


for jj = 1:(n-1)
matches = find( birthdays(jj) == birthdays(jj+1:n));
if ~isempty(matches)
n_matches = n_matches + 1;
break;
end
end
end

% Now calculate probability


prob = n_matches / n_trials;

A test program to determine the probability for groups of 2-40 people is shown below:

% Script file: test_birthday.m


%
% Purpose:
% To calculate the probability of 2 or more of n people
% having the same birthday, where "n" is a number between
% 2 and 40.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 10/11/11 S. J. Chapman Original code
%
% Define variables:
218
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% ii -- Number of people in group
% prob -- Probability of 2 or more with same birthday

% Calculate and display probabilities


fprintf(' n prob\n');
fprintf(' = ====\n');
for ii = 2:40
prob(ii) = birthday(ii);
fprintf(' %2d %0.4f\n',ii,prob(ii));
end

% Plot probabilities
plot(2:40,prob(2:40),'b-','LineWidth',2);
title('\bfProbability of 2 or more people with same birthday');
xlabel('\bfNumber of people in group');
ylabel('\bfProbability');
grid on;

When this program is executed, the results are:

>> test_birthday
n prob
= ====
2 0.0032
3 0.0082
4 0.0160
5 0.0275
6 0.0410
7 0.0569
8 0.0739
9 0.0937
10 0.1152
11 0.1418
12 0.1666
13 0.1975
14 0.2252
15 0.2527
16 0.2856
17 0.3180
18 0.3482
19 0.3811
20 0.4104
21 0.4462
22 0.4784
23 0.5115
24 0.5377
25 0.5703
26 0.5969
27 0.6267
28 0.6585
29 0.6807
30 0.7066
31 0.7292
219
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
32 0.7524
33 0.7730
34 0.7948
35 0.8148
36 0.8309
37 0.8487
38 0.8630
39 0.8777
40 0.8898

7.21 A program to calculate the false alarm rate as a function of the threshold setting above the mean noise level
is shown below. This program generates 10,000,000 Rayleigh-distributed noise samples2, and determines
the fraction of those samples which exceed each of 9 threshold levels. (Caution: The ten million-sample
array in this program may take a long time to execute on a memory-limited computer. If necessary, you
can cut down the sample size. However at least 100,000 (105) samples will be necessary to approximate a
false alarm rate of 10-4.)

% Script file: calc_cfar.m


%
% Purpose:
% To calculate the rate of false detections in a radar receiver
% as a function of detection threshold setting. The detection
% threshold is expressed as a ratio in dB.
%
% Record of revisions:

2 A random number generator on a Rayleigh distribution is created in Exercise 7.25.


220
© 2016 Cengage Learning®. 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/13/15 S. J. Chapman Original code
%
% Define variables:
% count -- Number of threshold crossings for each threshold
% ii -- Loop index
% mean_noise -- Mean noise amplitude
% n_samples -- Number of samples
% sample -- Samples of random noise
% thresh_db -- Threshold level expressed in dB
% thresh_v -- Threshold level expressed in volts

% Initialize threshold levels


n_samples = 10000000;
mean_noise = 10;
thresh_db = [ 5., 6., 7., 8., 9., 10., 11., 12., 13. ];
thresh_v = mean_noise .* 10.0 .^(thresh_db/20.);

% Calculate an array of 1,000,000 Rayleigh-distributed samples


% Get Rayleigh-distributed samples with a mean amplitude of 10 volts.
% Note from the previous problem that the function random_rayleigh has
% a mean amplitude of 1.25, so to get the desired amplitude of
% "mean_noise", we must multiply the output by mean_noise/1.25.
sample = mean_noise / 1.25 * random_rayleigh(1,n_samples);

% Count the number of threshold crossings for each threshold level.


for ii = 1:length(thresh_v)
count(ii) = sum( sample > thresh_v(ii) );
end

% Tell user about result.


fprintf('The false alarm rate versus threshold level is: \n');
for ii = 1:length(thresh_v)
fprintf(' Threshold = %5.1f dB Pfa = %14.5e\n', ...
thresh_db(ii), count(ii)/n_samples );
end

When this program is executed, the results are as shown below. To get a false alarm rate below 10-4, we
would need a threshold of 11 dB.

>> calc_cfar
The false alarm rate versus threshold level is:
Threshold = 5.0 dB Pfa = 8.42700e-002
Threshold = 6.0 dB Pfa = 4.45740e-002
Threshold = 7.0 dB Pfa = 2.00360e-002
Threshold = 8.0 dB Pfa = 7.27600e-003
Threshold = 9.0 dB Pfa = 2.01500e-003
Threshold = 10.0 dB Pfa = 4.27000e-004
Threshold = 11.0 dB Pfa = 5.90000e-005
Threshold = 12.0 dB Pfa = 7.00000e-006
Threshold = 13.0 dB Pfa = 1.00000e-006

221
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
7.22 A function gen_func that generates functions to evaluate polynomials of the form f ( x ) = ax 2 + bx + c ,
where a, b, and c are specified by the user, is shown below. This function creates and returns a handle to a
nested function eval_func, which evaluates the polynomial function for a given x and the values of a,
b, and c specified when the function handle was created.

function hndl = gen_func(a, b, c)


%GEN_FUNC Generate a polynomial function.
% Function GEN_FUNC generates a polynomial function
% of the form f(x) = a*x^2 + b*x + c, and returns a
% function handle to a function that evaluates the
% polynomial at a specific value of x.

% Define variables:
% a -- Coefficient of x^2
% b -- Coefficient of x
% c -- Constant coefficient
% hndl -- Handle to function "eval_func"
% msg -- Error message
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/20/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


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

% Return function handle


hndl = @eval_func;

% Nested function eval_func. This function evaluates


% the polynomial f(x) = a*x^2 + b*x + c for the specified
% values of a, b, c, and x.
function y = eval_func(x)
y = a*x.^2 + b*x + c;
end % function eval_func

end % function gen_func

A function to plot a function, specified by a function handle, between specified limits is shown below:

function plot_func(hndl, x1, x2)


%PLOT_FUNC Plot a function specified by a function handle.
% Function PLOT_FUNC plots the function specifed in the
% function handle between the limits [x1 x2].

% Define variables:
% hndl -- Handle to function "eval_func"
% msg -- Error message
% str -- Title string
% x -- X values to plot

222
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% x1 -- Starting value to plot
% x2 -- Ending value to plot
% y -- Y values to plot
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/20/15 S. J. Chapman Original code

% Check for a legal number of input arguments.


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

% Get the x values to plot


x = x1:0.1:x2;

% Get the y values to plot


y = hndl(x);

% Plot the function


plot(x,y,'LineWidth',2);
str = ['\bfPlot of polynomial between ' num2str(x1) ' and
' num2str(x2)];
title(str);
xlabel('\bfx');
ylabel('\bfy');
grid on;

end % function plotfunc

A script file to test these functions is shown below:

% Script file: test_gen_func.m


%
% Purpose:
% To test function gen_func. This program creates
% handles to two polynomials, and then plots them
% between specified limits using the function handle.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/20/15 S. J. Chapman Original code
%
% Define variables:
% h1 -- Handle to function f(x) = x^2 + 2*x + 1
% h2 -- Handle to function f(x) = x^2 + 4*x + 3
clear all

% Create polynomial function f(x) = x^2 + 2*x + 1


h1 = gen_func(1,2,1);

% Create polynomial function f(x) = x^2 + 4*x + 3


223
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
h2 = gen_func(1,4,3);

% Plot the first function between -3 and 3


figure(1);
plot_func(h1,-3,3);

% Plot the first function between -3 and 3


figure(2);
plot_func(h2,-3,3);

When this program is executed, the two resulting plots are:

224
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
7.23 To solve this problem, we must first express the differential equation in the form where the derivative of
vout ( t ) is equal to a function. This is Equation (7.15) from the problem statement:

dvout 1 1
=− vout ( t ) + vin ( t ) (7.15)
dt RC RC

We will use function ode45 to solve for the solution to this differential equation. The input voltage as a
function of time is calculated in the following function:

function result = vin(t)


%VIN Calculates the input voltage vs time.

% Define variables:
% t -- Time
% result -- Input voltage
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/20/15 S. J. Chapman Original code

% Calculate derivative
if t >= 0

% Voltage is 1 for seconds starting on an even number, and


% 0 for seconds starting on an odd number.
225
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
if mod(floor(t),2) == 0
result = 1;
else
result = -1;
end

else

% Before time 0
result = 0;

end

The function to calculate the derivative of the differential equation becomes:

function yprime = derivative_fn(t,y)


%DERIVATIVE_FN Calculates the derivative of the output voltage.

% Define variables:
% t -- Time (in days)
% y -- Vector of states (voltage)
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/20/15 S. J. Chapman Original code

% Set decay constant.


r = 1.0e6; % ohms
c = 1.0e-6; % farads
lambda = 1 / (r * c);

% Calculate derivative
yprime = lambda * vin(t) - lambda * y;

The final script file to calculate the output voltage is:

% Script file: rc_circuit.m


%
% Purpose:
% To calculate the ouput voltage from a simple RC
% circuit being driven by a square wave input voltage.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/20/15 S. J. Chapman Original code
%
% Define variables:
% odefun_handle -- Handle to function that defines the derivative
% tspan -- Duration to solve equation for
% yo -- Initial condition for equation
% t -- Array of solution times
226
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% y -- Array of solution values

% Get a handle to the function that defines the


% derivative.
odefun_handle = @derivative_fn;

% Solve the equation over the period 0 to 10 seconds


tspan = [0 10];

% Set the initial conditions


y0 = 0;

% Call the differential equation solver.


[t,y] = ode45(odefun_handle,tspan,y0);

% Plot the result


figure(1);
plot(t,y,'b-','LineWidth',2);
grid on;
title('\bfOutput Voltage');
xlabel('\bfTime (s)');
ylabel('\bf\itv_{out}');

The resulting output voltage is shown below:

227
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
7.24 To solve this problem, we must first express the differential equation in the form where the derivative of
v( t ) is equal to a function. This equation is

dv 1
=− v ( t ) + vin ( t )
dt RC

The input function vin is calculated in the following function:

function result = vin(t)

% Define variables:
% t -- Time
% result -- Input voltage
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/20/15 S. J. Chapman Original code

% Calculate derivative
if (t >= 0) & (t <= 5)
result = t;
else
result = 0;
end

The function to calculate the derivative of the differential equation becomes:

function yprime = fun1(t,y)


yprime = -y + vin(t);

The final script file to calculate the output voltage is:

% Script file: ode45_soln.m


%
% Purpose:
% This program solves a differential equation of the
% form dy/dt + 2 * y = 0, with the initial condition
% y(0) = 1.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 04/20/15 S. J. Chapman Original code
%
% Define variables:
% odefun_handle -- Handle to function that defines the derivative
% tspan -- Duration to solve equation for
% yo -- Initial condition for equation
% t -- Array of solution times
% y -- Array of solution values
228
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% Get a handle to the function that defines the
% derivative.
odefun_handle = @fun1;

% Solve the equation over the period 0 to 5 seconds


tspan = [0 10];

% Set the initial conditions


y0 = 0;

% Call the differential equation solver.


[t,y] = ode45(odefun_handle,tspan,y0);

% Plot the result


figure(1);
plot(t,y,'b-','LineWidth',2);
grid on;
title('\bfSolution of Differential Equation');
xlabel('\bfTime (s)');
ylabel('\bf\itv(t)');

The resulting output voltage is shown below:

229
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
7.25 A function to calculate random values from a Rayleigh distribution is shown below:

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/23/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
% ==== ========== =====================
230
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
% 04/23/15 S. J. Chapman Original code
%
% 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

231
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
232
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

You might also like