• Home
  • Textbooks
  • MATLAB Programming for Engineers
  • User-Defined Functions

MATLAB Programming for Engineers

Stephen J.Chapman

Chapter 5

User-Defined Functions - all with Video Answers

Educators


Chapter Questions

00:31

Problem 1

What is the difference between a script file and a function?

Weston Bell-Geddes
Weston Bell-Geddes
Numerade Educator
00:43

Problem 2

When a function is called, how is data passed from the caller to the function, and how are the results of the function returned to the caller?

Sheryl Ezze
Sheryl Ezze
Numerade Educator
03:52

Problem 3

What are the advantages and disadvantages of the pass-by-value scheme used in MATLAB?

Arulmozhi T
Arulmozhi T
Numerade Educator
01:21

Problem 4

Modify the selection sort function developed in this chapter so that it accepts a second optional argument, which may be either ' up ' or "down'. If the argument is 'up', sort the data in ascending order. If the argument is 'dewn', sort the data in descending order. If the argument is missing, the default case is to sort the data in ascending order. (Be sure to handle the case of invalid arguments, and be sure to include the proper help information in your function.)

Morgan Cheatham
Morgan Cheatham
Numerade Educator
00:36

Problem 5

Write a function that uses function randono to generate a random value in the range $[-1.0,1.0)$. Make random0 a subfunction of your new function.

Harsh Gadhiya
Harsh Gadhiya
Numerade Educator
06:48

Problem 6

Write a function that uses function randomo to generate a random value in the range [low, high), where low and high are passed as calling arguments. Make random0 a private function called by your new function.

Tarandeep Singh
Tarandeep Singh
Numerade Educator
00:59

Problem 7

Dice Simulation. It is often useful to be able to simulate the throw of a fair die. Write a MATLAB function dice that simulates the throw of a fair die by returning some random integer between 1 and 6 every time that it is called. (Hint: Call randomo to generate a randem number. Divide the possible values out of random0 into six equal intervals, and return the number of the interval that a given random value falls into.)

Sherrie Fenner
Sherrie Fenner
Numerade Educator
View

Problem 8

Read Traffic Density. Function random0 produces a number with a uniform probability distribution in the range $[0.0,1.0)$. This function is suitable for simulating random events if each outcome has an equal probability of occurring. However, in many events the probability of occurrence is not equal for every event, and a uniform probability distribution is not suitable for simulating such events.

For example, when traffic engineers studied the number of cars passing a given location in a time interval of length $t$, they discovered that the probability of $k$ cars passing during the interval is given by the equation
$$
P(k, t)=e^{-\lambda t} \frac{(\lambda t)^{4}}{k !} \text { for } t \geq 0, \lambda>0, \text { and } k=0,1,2, \ldots
$$
This probability distribution is known as the Poisson distribution: it occurs in many applications in science and engineering. For example, the number of calls $k$ to a telephone switchboard in time interval $t$, the number of bacteria $k$ in a specified volume $t$ of liquid, and the number of failures $k$ of a complicated system in time interval $t$ all have Poisson distributions.

Write a function to evaluate the Poisson distribution for any $k, t$, and A. Test your function by calculating the probability of $0,1,2, \ldots, 5$ cars passing a particular point on a highway in I minute, given that $\lambda$ is $1.6$ per minute for that highway. Plot the Poisson distribution for $t=1$ and $\lambda=1.6$.

Victor Salazar
Victor Salazar
Numerade Educator
01:31

Problem 9

Write three MATLAB functions to caiculate the hyperbolic sine, cosine, and tangent functions.
$$
\sinh (x)=\frac{e^{x}-e^{-x}}{2}, \cosh (x)=\frac{e^{x}+e^{-x}}{2}, \tanh (x)=\frac{e^{x}-e^{-x}}{e^{x}+e^{-x}}
$$ Use your functions to plot the shapes of the hyperbolic sine, cosine, and tangent functions.

Ernest Castorena
Ernest Castorena
Numerade Educator
02:09

Problem 10

Cross Product. Write a function to calculate the cross product of two vectors $\mathbf{V}_{1}$ and $\mathbf{V}_{2}$
$\mathbf{V}_{1} \times \mathbf{V}_{2}=\left(V_{y 1} V_{x 2}-V_{v 2} V_{21}\right) \mathbf{i}+\left(V_{21} V_{x 2}-V_{22} V_{x 1}\right) \mathbf{j}+\left(V_{41} V_{v 2}-V_{x 2} V_{v 1}\right) \mathbf{k}$ where $\mathbf{V}_{1}=V_{x 1} \mathbf{i}+V_{x 1} \mathbf{j}+V_{z 1} \mathbf{k}$ and $\mathbf{V}_{2}=V_{x 2} \mathbf{i}+{y_{12}} \mathbf{j}+y_{x 2} \mathbf{k}$. Note that this function will return a real array as its result. Use the function to calculate the cross product of the two vectors $V_{1}=[-2,4,0.5]$ and $V_{2}=$ $[0.5,3,2]$.

Jose Hannan
Jose Hannan
Numerade Educator
03:04

Problem 11

Sort with Carry. It is often useful to sort an array are1 into ascending order, while simultancously carrying along a second array arr2. In such a sort, each time an element of array arrl is exchanged with another element of arr1, the corresponding elements of array arr2 are also swapped. When the sort is over, the elements of array arri are in ascending order, whereas the elements of array arr 2 that were associated with particular elements of array arrl are still associated with them. For example, suppose we have the following two arrays.
$\begin{array}{ccc}\text { Element } & \text { arr1 } & \frac{\operatorname{arc} 2}{1 .} \\ 1 . & 6 . & 0 . \\ 2 . & 1 . & 10 . \\ 3 . & 2 . & 10 .\end{array}$
After sorting array arrl while carrying along array arr2, the contents of the two arrays will be
$\begin{array}{ccc}\text { Element } & \text { arr1 } & \text { are2 } \\ 1 . & 1 . & 0 . \\ 2 . & 2 . & 10 . \\ 3 . & 6 . & 1 .\end{array}$
Write a function to sort one real array into ascending order while carrying along a second one. Test the function with the following two 9 -element arrays.
$$
\begin{aligned}
&a=[-1, \quad 12, \quad-6, \quad 17, \quad-23,0,5, \quad 1,-1]: \\
&b=[-31,101,36,-17, \quad 0,10,-8,-1,-1]=
\end{aligned}
$$

Morgan Cheatham
Morgan Cheatham
Numerade Educator
07:13

Problem 12

Use the Help Browser to look up information about the standard MATLAB function sortrows and compare the performance of sortrows with the sort-with-carry function created in the previous exercise. To do this, create two copies of a $1000 \times 2$ element array containing random values, and sort column 1 of each array while carrying along column 2 using both functions. Determine the execution times of each sort function using tic and toe. How does the speed of your function compare with the speed of the standard function sorerows?

Victor Salazar
Victor Salazar
Numerade Educator
10:14

Problem 13

Figure $5.7$ shows two ships stearning on the ocean. Ship 1 is at position $\left(x_{1}, y_{1}\right)$ and steaming on heading $\theta_{1}$. Ship 2 is at position $\left(x_{2}, y_{2}\right)$ and steaming on heading $\theta_{2}$. Suppose that Ship I makes radar contact with an object at range $r_{1}$ and bearing $e_{1}$. Write a MATLAB function that will calculate the range $r_{2}$ and bearing $\sigma_{2}$ at which Ship 2 should see the object.

Suman Saurav Thakur
Suman Saurav Thakur
Numerade Educator
01:46

Problem 14

Minima and Maxima of a Function. Write a function that attempts to locate the maximum and minimum values of an arbitrary function $f(x)$ over a certain range. The function being evaluated should be passed to the function as a calling argument. The function should have the following input arguments.
first_value .. The first value of $x$ to search
last_value
num_steps
func
The function should have the following output arguments.
xamin
min_value
xmax
max_value - The value of $x$ at which the minimum value of $f(x)$ found $} \\{\hline} \end{array}$
Be sure to check that there are a valid number of input arguments and that the MATLAB help and lookfor commands are properly supported.

Aman Gupta
Aman Gupta
Numerade Educator
01:02

Problem 15

Write a test program for the function generated in the previous exercise. The test program should pass to the function function the user-defined function $f(x)=x^{3}-5 x^{2}+5 x-2$, and search for the minimum and maximum in 200 steps over the range $-1 \leq x \leq 3$. It should print out the resalting minimum and maximum values.

AG
Ankit Gupta
Numerade Educator
01:03

Problem 16

Derivative of a Function. The derivative of a continuous function $f(x)$ is defined by the equation
$$
\frac{d}{d x} f(x)=\lim _{\Delta x=0} \frac{f(x+\Delta x)-f(x)}{\Delta x}
$$
In a sampled function, this definition becomes
$$
f^{\prime}\left(x_{i}\right)=\frac{f\left(x_{i+1}\right)-f\left(x_{i}\right)}{\Delta x}
$$
where $\Delta x=x_{i+1}-x_{i}$ Assume that a vector vect contains nsamp samples of a function taken at a spacing of $d x$ per sample. Write a function that will calculate the derivative of this vector from Equation (5.12). The function should check to make sure that $\mathrm{dx}$ is greater than zero to prevent divide-by-zero errors in the function.

To check your function, you should generate a data set whose derivative is known, and compare the result of the function with the known correct answer. A good choice for a test function is $\sin x$. From elemen$\operatorname{tary}$ calculus, we know that $\frac{d}{d x}(\sin x)-\cos x$. Generate an input vector containing 100 values of the function $\sin x$ starting at $x=0$ and using a step size $\Delta x$ of $0.05$. Take the derivative of the vector with your function, and then compare the resulting answers to the known correct answer. How close did your function come to calculating the correct value for the derivative?

Carson Merrill
Carson Merrill
Numerade Educator
05:58

Problem 17

Derivative in the Presence of Noise. We will now explore the effects of input noise on the quality of a numerical derivative. First, generate an input vector containing 100 values of the function $\sin x$ starting at $x=0$, using a step size $\Delta x$ of $0.05$, just as you did in the previous problem. Next, use function randomo to generate a small amount of random noise with a maximum amplitude of $\pm 0.02$, and add that random noise to the samples in your input vector (see Figure 5.8). Note that the peak amplitude of the noise is only $2 \%$ of the peak amplitude of your signal, since the maximum value of $\sin x$ is 1. Now take the derivative of the function using the derivative function that you developed in the last problem. How close to the theoretical value of the derivative did you come?

Khoobchandra Agrawal
Khoobchandra Agrawal
Numerade Educator
04:35

Problem 18

Linear Least-Squares Fit. Develop a function that will calculate slope $m$ and intercept $b$ of the least-squares line that best fits an input data set. The input data points $(x, y)$ will be passed to the function in two input arrays, $x$ and $y$. (The equations describing the slope and intercept of the least-squares line are given in Example $4.7$ in the previous chapter.) Test your function using a test program and the 20-point input data set given in Table 5.2.

Eric Mockensturm
Eric Mockensturm
Numerade Educator
03:59

Problem 19

Correlation Coefficient of Least-Squares Fit. Develop a function that will calculate both the slope $m$ and intercept $b$ of the least-squares line that where
$\sum x$ is the sum of the $x$ values.
$\sum y$ is the sum of the $y$ values.
$\sum x^{2}$ is the sum of the squares of the $x$ values.
$\sum y^{2}$ is the sum of the squares of the $y$ values.
$\sum x y$ is the sum of the products of the corresponding $x$ and $y$ values.
$n$ is the number of points included in the fit.
Test your function using a test driver program and the 20 -point input data set given in the previous problem.

Jon Southam
Jon Southam
Numerade Educator
02:32

Problem 20

The Birthday Problem. The birthday problem is: if there is a group of $n$ people in a room, what is the probability that two or more of them have the same birthday? It is possible to determine the answer to this question by simulation. Write a function that calculates the probabulity that two or more of $n$ people will have the same birthday, where $n$ is a calling argument. (Hint: To do this, the function should create an array of size $n$ and generate $n$ birthdays in the range 1 to 365 randomly. It should then check to see if any of the $n$ birthdays are identical. The function should perform this experiment at least 5000 times and calculate the fraction of those times in which two or more people had the same birthday.) Write a test program that calculates and prints out the probability that 2 or more of $n$ people will have the same birthday for $n=2,3, \ldots, 40$.

Harsh Gadhiya
Harsh Gadhiya
Numerade Educator
01:25

Problem 21

Use function random0 to generate a set of three arrays of random numbers. The three arrays should be 100,1000, and 2000 elements long. Then, use functions $t i c$ and toc to determine the time that it takes function ssort to sort each array. How does the elapsed time to sort increase as a function of the number of elements being sorted? (Hint: On a fast computer, you will need to sort cach array many times and calculate the average sorting time in order to overcome the quantization error of the system clock.)

Nick Johnson
Nick Johnson
Numerade Educator
01:16

Problem 22

Gaussian (Normal) Distribution. Function randomo returns a uniformly distributed random variable in the range $[0,1)$, which means that there is an equal probability of any given number in the range occurring on a given call to the function. Another type of random distribution is the Gaussian distribution, in which the random value takes on the classic bellshaped curve shown in Figure 5.9. A Gaussian distribution with an average of $0.0$ and a standard deviation of $1.0$ is called a standardized normal distribution, and the probability of any given value occurring in the standardized normal distribution is given by the equation
$$
p(x)=\frac{1}{\sqrt{2 \pi}} e^{-x^{2} / 2}
$$
It is possible to generate a random variable with a standardized normal distribution starting from a random variable with a uniform distribution in the range $[-1,1)$ as follows.
1. Select two uniform random variables $x_{1}$ and $x_{2}$ from the range $[-1,1)$ such that $x_{1}^{2}+x_{2}^{2}<1$. To do this, generate two uniform random variables in the range $[-1,1)$, and see if the sum of their squares happens to be less than $1.0$. If so, use them. If not, try again.
2. Then each of the values $y_{1}$ and $y_{2}$ in the equations that follow will be a normally distributed random variable. $$
\begin{aligned}
&y_{1}=\sqrt{\frac{-2 \ln r}{r}} x_{1} \\
&y_{2}=\sqrt{\frac{-2 \ln r}{r} x_{2}}
\end{aligned}
$$
where
$$
r=x_{1}^{2}+x_{2}^{2}
$$
a In is the natural logarithm (log to the base e). Write a function that returns a normally distributed random value cach time that it is called. Test your function by getting 1000 random values, calculating the standard deviation, and plotting a histogram of the distribution. How close to $1.0$ was the standard deviation?

Victor Salazar
Victor Salazar
Numerade Educator
01:07

Problem 23

Gravitational Force. The gravitational force $F$ between two bodies of masses $m_{1}$ and $m_{2}$ is given by the equation
$$
F=\frac{G m_{1} m_{2}}{r^{2}}
$$
where $G$ is the gravitational constant $\left(6.672 \times 10^{-11} \mathrm{~N} \mathrm{~m}^{2} / \mathrm{kg}^{2}\right), m_{1}$ and $m_{2}$ are the masses of the bodies in kilograms, and $r$ is the distance between the two bodies. Write a function to calculate the gravitational force between two bodies given their masses and the distance between them. Test your function by determining the force on an $800-\mathrm{kg}$ satellite in orbit $38,000 \mathrm{~km}$ above the Earth. (The mass of the Earth is $5.98 \times 10^{24} \mathrm{~kg}$.)

Carson Merrill
Carson Merrill
Numerade Educator
View

Problem 24

Rayleigh Distribution. The Rayleigh distribution is another random number distribution that appears in many practical problems. A Rayleighdistributed random value can be created by taking the square root of the sum of the squares of two normally distributed random values. In other words, to generate a Rayleigh-distributed random value $r$ get two normally distributed random values $\left(n_{1}\right.$ and $\left.n_{2}\right)$, and perform the following calculation.
$$
r=\sqrt{n_{1}^{2}+n_{2}^{2}}
$$
a. Create a function rayleigh $(\mathrm{n}, \mathrm{m})$ that returns an $\mathrm{n} \mathrm{x} \mathrm{m}$ array of Rayleigh-distributed random numbers. If only one argument is supplied [rayleigh $(\mathrm{n})$ ], the function should return an $\mathrm{n} \times \mathrm{n}$ array of Rayleigh-distributed random numbers. Be sure to design your function with input argument checking and with proper documentation for the MATLAB help system.
b. Test your function by creating an array of 20,000 Rayleigh-distributed random values and plotting a histogram of the distribution. What does the distribution look like?
c. Determine the mean and standard deviation of the Rayleigh distribution.

Victor Salazar
Victor Salazar
Numerade Educator
02:35

Problem 25

Constant False Alarm Rate (CFAR). A simplified radar receiver chain is shown in Figure $5.10 a$. When a signal is received in this receiver, it contains both the desired information (returns from targets) and thermal noise. After the detection step in the receiver, we would like to be able to pick out received target returns from the thermal noise background. We can do this be setting a threshold level, and then declaring that we see a target whenever the signal crosses that threshold. Unfortunately, it is

Priyank Sharma
Priyank Sharma
Numerade Educator
View

Problem 26

Probability of Detection $\left(P_{2}\right)$ versus Probability of False Alarm $\left(P_{\text {a }}\right)$. The signal strength returned by a radar target usually fluctuates over time. The target will be detected if its signal strength exceeds the detection threshold for any given look. The probability that the target will be detected can be calculated as
$$
P_{i=}=\frac{\text { Number of Target Detections }}{\text { Total Number of Looks }}
$$
Suppose that a specific radar looks repeatedly in a given direction. On cach look, the range between $10 \mathrm{~km}$ and $20 \mathrm{~km}$ is divided into 100 independent range samples (called range gates). One of these range gates contains a target whose amplitude has a normal distribution with a mean amplitude of 7 volts and a standard deviation of I volt. All 100 of the range gates contain system noise with a mean amplitude of 2 volts and a Rayleigh distribution. Determine both the probability of target detection $P_{d}$ and the probability of a false alarm $P_{1,}$ on any given look for detection thresholds of $8.0,8.5,9.0,9.5,10.0,10.5,11.0,11.5$, and $12.0 \mathrm{~dB}$. What threshold would you use for detection in this radar? (Hint: Perform the experiment many times for each threshold and average the results to determine valid probabilities.)

Jason Gerber
Jason Gerber
Numerade Educator