## Stephen J. Chapman

## Chapter 5

## Loops and Vectorization - all with Video Answers

## Educators

Chapter Questions

Write the MATLAB statements required to calculate $y(t)$ from the equation

$$

y(t)=\left\{\begin{array}{cc}

-3 t^2-4 & t \geq 0 \\

3 t^2-4 & t<0

\end{array}\right.

$$

for values of $t$ between -9 and 9 in steps of 0.5 . Use loops and branches to perform this calculation.

Linh Vu

Numerade Educator

Rewrite the statements required to solve Exercise 5.1 using vectorization.

Arden Mccarthy

Numerade Educator

Write the MATLAB statements required to calculate and print out the squares of all the even integers between 0 and 50 . Create a table consisting of each integer and its square, with appropriate labels over each column.

Sherrie Fenner

Numerade Educator

Write an M-file to evaluate the equation $y(x)=x^2-4 x+5$ for all values of $x$ between -1 and 3, in steps of 0.1. Do this twice, once with a for loop and once with vectors. Plot the resulting function using a 3-point-thick dashed red line.

Check back soon!

Write an M-file to calculate the factorial function $\mathrm{n}$ !, as defined in Example 5.2. Be sure to handle the special case of 0 !. Also, be sure to report an error if $n$ is negative or not an integer.

Carson Merrill

Numerade Educator

Examine the following for statements and determine how many times each loop will be executed.

(a) for ii $=-32768: 32767$

(b) for ii $=32768: 32767$

(c) for $k k=2: 4: 3$

(d) for $j j=$ ones $(5,5)$

Check back soon!

Examine the following for loops and determine the value of ires at the end of each of the loops, and also the number of times each loop executes.

(a)

```

ires = 0;

for index = -12:12

ires = ires + 1;

end

```

(b)

```

ires = 0;

for index = 10:-2:1

if index == 6

continue;

end

ires = ires + index;

end

```

(c)

```

ires = 0;

for index = 10:-2:1

if index == 6

break;

end

ires = ires + index;

end

```

(d)

```

ires = 0;

for index1 = 10:-2:1

for index 2 = 2:2:index1

if index 2 == 6

break

end

ires = ires + index2;

end

end

```

Check back soon!

Examine the following while loops and determine the value of ires at the end of each of the loops, and the number of times each loop executes.

(a)

```

ires = 1;

while mod(ires,16) ~= 0

ires = ires + 1;

end

```

(b) ires $=2$;

while ires $<=100$

ires $=$ ires^ $^{\wedge}$;

end

(c) ires $=2$;

while ires $>100$

ires $=$ ires $^{\wedge} 2$;

end

Check back soon!

What is contained in array arr1 after each of the following sets of statements is executed?

(a)

$\operatorname{mask}=\bmod (\operatorname{arr} 1,2)==0$;

$\operatorname{arr1}(\mathrm{mask})=-\operatorname{arr} 1($ mask);

(b)

```

arr2 = arr1 <= 5;

arr1(arr2) = 0;

arr1(~\operatorname{arr2) = arr1(~arr2).^}2;

```

Check back soon!

How can a logical array be made to behave as a logical mask for vector operations?

Shelby Mohamed

Numerade Educator

Modify program ball from Example 5.7 by replacing the inner for loops with vectorized calculations.

Check back soon!

Modify program ball from Example 5.7 to read in the acceleration due to gravity at a particular location, and to calculate the maximum range of the ball for that acceleration. After modifying the program, run it with accelerations of $-9.8 \mathrm{~m} / \mathrm{s}^2,-9.7 \mathrm{~m} / \mathrm{s}^2$, and $-9.6 \mathrm{~m} / \mathrm{s}^2$. What effect does the reduction in gravitational attraction have on the range of the ball? What effect does the reduction in gravitational attraction have on the best angle $\theta$ at which to throw the ball?

Ceren Uzun

Texas Tech University

Modify program ball from Example 5.7 to read in the initial velocity with which the ball is thrown. After modifying the program, run it with initial velocities of $10 \mathrm{~m} / \mathrm{s}, 20 \mathrm{~m} / \mathrm{s}$, and $30 \mathrm{~m} / \mathrm{s}$. What effect does changing the initial velocity $v_0$ have on the range of the ball? What effect does it have on the best angle $\theta$ at which to throw the ball?

Garrett Bess

Numerade Educator

Program 1sqfit from Example 5.6 required you to specify the number of input data points before entering the values. Modify the program so that it reads an arbitrary number of data values using a while loop, and stops reading input values when the user presses the Enter key without typing any values. Test your

program using the same two data sets that were used in Example 5.6.

Check back soon!

Modify program 1sqfit from Example 5.6 to read its input values from an ASCII file named input1. dat. The data in the file will be organized in rows, with one pair of $(x, y)$ values on each row, as shown below:

\begin{tabular}{ll}

1.1 & 2.2 \\

2.2 & 3.3

\end{tabular}

. .

Use the load function to read the input data. Test your program using the same two data sets that were used in Example 5.6.

Check back soon!

Modify program 1sqfit from Example 5.6 to read its input values from a user-specified ASCII file named input 1. dat. The data in the file will be organized in rows, with one pair of $(x, y)$ values on each row, as shown below:

$$

\begin{array}{ll}

1.1 & 2.2 \\

2.2 & 3.3 \\

\ldots &

\end{array}

$$

Use the textread function to read the input data. Test your program using the same two data sets that were used in Example 5.6.

Check back soon!

Factorial Function MATLAB includes a standard function called factorial to calculate the factorial function. Use the MATLAB help system to look up this function, and then calculate 5 !, 10!, and 15 ! using both the program in Example 5.2 and the factorial function. How do the results compare?

Carson Merrill

Numerade Educator

Higher-Order Least-Squares Fits Function polyfit allows you to fit a polynomial of any order to an input data set, not just a straight line. Write a program that reads its input values from an ASCII file and fits both a straight line and a parabola to the data. The program should plot both the original data and the two fitted lines.

Test your program using the data in the file input 2 . dat, which is available on the book's website. Is the first-order or second-order fit a better representation of this data set? Why?

Check back soon!

Running Average Filter Another way of smoothing a noisy data set is with a running average filter. For each data sample in a running average filter, the program examines a subset of $n$ samples centered on the sample under test, and it replaces that sample with the average value from the $n$ samples. (Note: For points near the beginning and the end of the data set, use a smaller number of samples in the running average, but be sure to keep an equal number of samples on either side of the sample under test.)

Write a program that allows you to specify the name of an input data set and the number of samples to average in the filter and then performs a running average filter on the data. The program should plot both the original data and the smoothed curve after the running average filter.

Test your program using the data in the file input 3 . dat, which is available on the book's Web site.

Check back soon!

Median Filter Another way of smoothing a noisy data set is with a median filter. For each data sample in a median filter, the program examines a subset of $n$ samples centered on the sample under test, and it replaces that sample with the median value from the $n$ samples. (Note: For points near the beginning and the end of the data set, use a smaller number of samples in the median calculation, but be sure to keep an equal number of samples on either side of the sample under test.) This type of filter is very effective against data sets containing isolated "wild" points that are very far away from the other nearby points.

Write a program that allows you to specify the name of an input data set and the number of samples to use in the filter and then performs a median filter on the data. The program should plot both the original data and the smoothed curve after the median filter.

Test your program using the data in the file input 3 . dat, which is available on the book's website. Is this filter better or worse than the running average filter for smoothing this data set? Why?

Check back soon!

Residuals Residuals are the differences between the original data points and the points from the fitted curve for a particular fit. An average measure of the residuals from a plot is often calculated in a root-mean-square sense as follows:

$$

\text { residuals }=\sqrt{\frac{1}{N} \sum_{i=1}^N\left(y_i-\bar{y}_i\right)^2}

$$

where $y_i$ is the $i$ th data value and $\bar{y}_i$ is the value of the fitted polynomial evaluated at the $i$ th data value. In general, the lower the residuals, the better the fitted line matches the original data. Also, a fit is better if it is unbiased, meaning that there are about as many values below the fitted line as above it. Modify the program in Exercise 5.18 to compute and display the residuals from the plot on a separate set of axes, and compute the average residuals from Equation (5.16). Compute and plot the residuals using the data in the file input2.dat, and compare the residuals for the first- and second- order fits. Is the first-order or second-order fit a better representation of this data set? Why?

Tyler Moulton

Numerade Educator

Fourier Series A Fourier series is an infinite series representation of a periodic function in terms of sines and cosines at a fundamental frequency (matching the period of the waveform) and multiples of that frequency. For example, consider a square wave function of period $L$, whose amplitude is 1 for $0-L / 2,-1$ for $L / 2-L$, 1 for $L-3 L / 2$, etc. This function is plotted in Figure 5.15. This function can be represented by the Fourier series

$$

f(x)=\sum_{n=1,3,5, \ldots}^{\infty} \frac{1}{n} \sin \left(\frac{n \pi x}{L}\right)

$$

Plot the original function assuming $L=1$, and calculate and plot Fourier series approximations to that function containing 3,5 , and 10 terms.

Chai Santi

Numerade Educator

Program doy in Example 5.3 calculates the day of year associated with any given month, day, and year. As written, this program does not check to see if the data entered by the user is valid. It will accept nonsense values for months and

days, and it will do calculations with them to produce meaningless results. Modify the program so that it checks the input values for validity before using them. If the inputs are invalid, the program should tell the user what is wrong, and quit. The year should be a number greater than zero, the month should be a number between 1 and 12, and the day should be a number between 1 and a maximum that depends on the month. Use a switch construct to implement the bounds checking performed on the day.

Check back soon!

Write a MATLAB program to evaluate the function

$$

y(x)=\ln \frac{1}{1-x}

$$

for any user-specified value of $x$, where $\ln$ is the natural logarithm (logarithm to the base $e$ ). Write the program with a while loop, so that the program repeats the calculation for each legal value of $x$ entered into the program. When an illegal value of $x$ is entered, terminate the program. (Any $x \geq 1$ is considered an illegal value.)

Amy Jiang

Numerade Educator

Traffic Light Modify the traffic light program developed in Example 4.5 to create a table of traffic light colors in each direction as a function of time at 1 second intervals for time $0 \leq t<120 \mathrm{~s}$.

Check back soon!

In 2009, individual citizens and residents of Australia paid the following income taxes:

( FIGURE CAN'T COPY )

$$

\begin{array}{ll}

\hline \text { Taxable Income }(\text { in } A \$) & \text { Tax on This Income } \\

\hline \$ 0-\$ 6,000 & \text { None } \\

\$ 6,001-\$ 34,000 & 15 \notin \text { for each } \$ 1 \text { over } \$ 6,000 \\

\$ 34,001-\$ 80,000 & \$ 4,200 \text { plus } 30 \notin \text { for each } \$ 1 \text { over } \$ 34,000 \\

\$ 80,001-\$ 180,000 & \$ 18,000 \text { plus } 40 \notin \text { for each } \$ 1 \text { over } \$ 80,000 \\

\text { Over } \$ 180,000 & \$ 58,000 \text { plus } 45 \text { for each } \$ 1 \text { over } \$ 180,000 \\

\hline

\end{array}

$$

In addition, a flat 1.5 percent Medicare levy was charged on all income. Write a program that plots the effective percent tax paid by an individual as a function

of income for taxable incomes from $$\$ 0$$ to $$\$ 300,000$$ in increments of $$\$ 1,000$$. Note that the effective tax rate is defined as

$$

\text { effective tax }=\frac{\text { actual tax paid }}{\text { actual taxable income }} \times 100 \%

$$

Carson Merrill

Numerade Educator

Fibonacci Numbers The $n$th Fibonacci number is defined by the following recursive equations:

$$

\begin{aligned}

f(1) & =1 \\

f(2) & =2 \\

f(n) & =f(n-1)+f(n-2)

\end{aligned}

$$

Therefore, $f(3)=f(2)+f(1)=2+1=3$ and so forth for higher numbers. Write an M-file to calculate and write out the $n$th Fibonacci number for $n>2$, where $n$ is input by the user. Use a while loop to perform the calculation.

Sriram Soundarrajan

Numerade Educator

Current through a Diode The current flowing through the semiconductor diode shown in Figure 5.16 is given by the equation

$$

i_D=I_0\left(e^{\stackrel{\# H}{H}}-1\right)

$$

where

$i_D=$ the voltage across the diode, in volts

$v_D=$ the current flow through the diode, in amps

$I_0=$ the leakage current of the diode, in amps

$q=$ the charge on an electron, $1.602 \times 10^{-19}$ coulombs

$k=$ Boltzmann's constant, $1.38 \times 10^{-23}$ joule $/ \mathrm{K}$

$T=$ temperature, in kelvins (K)

The leakage current $I_0$ of the diode is $2.0 \mu \mathrm{A}$. Write a program to calculate the current flowing through this diode for all voltages from $-1.0 \mathrm{~V}$ to $+0.6 \mathrm{~V}$, in $0.1 \mathrm{~V}$ steps. Repeat this process for the following temperatures: $75^{\circ} \mathrm{F}, 100^{\circ} \mathrm{F}$, and $125^{\circ} \mathrm{F}$. Create a plot of the current as a function of applied voltage, with the curves for the three different temperatures appearing as different colors.

Sheh Lit Chang

University of Washington

Tension on a Cable A $100-\mathrm{kg}$ object is to be hung from the end of a rigid $2-\mathrm{m}$ horizontal pole of negligible weight, as shown in Figure 5.17. The pole is attached to a wall by a pivot and is supported by a $2-\mathrm{m}$ cable that is attached to the wall at a higher point. The tension on this cable is given by the equation

( FIGURE CAN'T COPY )

$$

T=\frac{W \cdot l c \cdot l p}{d \sqrt{l p^2-d^2}}

$$

where $T$ is the tension on the cable, $W$ is the weight of the object, $l c$ is the length of the cable, $l p$ is the length of the pole, and $d$ is the distance along the pole at which the cable is attached. Write a program to determine the distance $d$ at which to attach the cable to the pole in order to minimize the tension on the cable. To do this, the program should calculate the tension on the cable at regular $0.1-\mathrm{m}$ intervals from $d=0.3 \mathrm{~m}$ to $d=1.8 \mathrm{~m}$, and should locate the position $d$ that produces the minimum tension. Also, the program should plot the tension on the cable as a function of $d$, with appropriate titles and axis labels.

Supratim Pal

Numerade Educator

Modify the program created in Exercise 5.29 to determine how sensitive the tension on the cable is to the precise location $d$ at which the cable is attached. Specifically, determine the range of $d$ values that will keep the tension on the cable within 10 percent of its minimum value.

Eric Mockensturm

Numerade Educator

Fit the following data using a cubic spline fit, and plot the fitted function over the range $0 \leq t \leq 10$.

$$

\begin{array}{ll}

\hline t & y(t) \\

\hline 0 & 0 \\

1 & 0.5104 \\

2 & 0.3345 \\

3 & 0.0315 \\

4 & -0.1024 \\

5 & -0.0787

\end{array}

$$

( TABLE CAN'T COPY )

These data points are derived from the function

$$

y(t)=e^{-0.5 s} \sin t

$$

How close does the fitted function come to the original values? Plot both of them on the same set of axes, and compare the original with the curve resulting from the spline fit.

Check back soon!

Area of a Parallelogram The area of a parallelogram with two adjacent sides defined by vectors $\mathbf{A}$ and $\mathbf{B}$ can be found from Equation (5.24) (see Figure 5.18).

$$

\text { area }=|\mathbf{A} \times \mathbf{B}|

$$

Write a program to read vectors $\mathbf{A}$ and $\mathbf{B}$ from the user, and calculate the resulting area of the parallelogram. Test your program by calculating the area of a parallelogram bordered by vectors $\mathbf{A}=10 \hat{\mathrm{i}}$ and $\mathbf{B}=5 \hat{\mathbf{i}}+8.66 y_2 \hat{\mathbf{j}}$.

Carlos Pinilla

Numerade Educator

Area of a Rectangle The area of the rectangle in Figure 5.19 is given by Equation (5.25) and the perimeter of the rectangle is given by Equation (5.26).

$$

\begin{gathered}

\text { area }=W \times H \\

\text { perimeter }=2 W+2 H

\end{gathered}

$$

Assume that the total perimeter of a rectangle is limited to 10 , and write a program that calculates and plots the area of the rectangle as its width is varied from the smallest possible value to the largest possible value. At what width is the area of the rectangle maximized?

( FIGURE CAN'T COPY )

Destin Priester

Numerade Educator

Bacterial Growth Suppose that a biologist performs an experiment in which he or she measures the rate at which a specific type of bacterium reproduces asexually in different culture media. The experiment shows that in Medium A the bacteria reproduce once every 60 minutes, and in Medium B the bacteria reproduce once every 90 minutes. Assume that a single bacterium is placed on each culture medium at the beginning of the experiment. Write a program that calculates and plots the number of bacteria present in each culture at intervals of three hours from the beginning of the experiment until 24 hours have elapsed. Make two plots, one a linear $x y$ plot and the other a linear-log (semilogy) plot. How do the numbers of bacteria compare on the two media after 24 hours?

Manan Sheel

Numerade Educator

Decibels Engineers often measure the ratio of two power measurements in decibels, or $\mathrm{dB}$. The equation for the ratio of two power measurements in decibels is

$$

\mathrm{dB}=10 \log _{10} \frac{P_2}{P_1}

$$

where $P_2$ is the power level being measured and $P_1$ is some reference power level. Assume that the reference power level $P_1$ is 1 watt, and write a program that calculates the decibel level corresponding to power levels between 1 and 25 watts in $1.0 \mathrm{~W}$ steps. Plot the $\mathrm{dB}$-versus-power curve on a log-linear scale.

Linh Vu

Numerade Educator

Geometric Mean The geometric mean of a set of numbers $x_1$ through $x_n$ is defined as the $n$th root of the product of the numbers:

$$

\text { geometric mean }=\sqrt[n]{x_1 x_2 x_3 \cdots x_n}

$$

Write a MATLAB program that will accept an arbitrary number of positive input values and calculate both the arithmetic mean (i.e., the average) and the geometric mean of the numbers. Use a while loop to get the input values, and enter a negative number to terminate the loop after all values have been entered. Test your program by calculating the average and geometric mean of the four numbers $10,5,2$, and 5 .

Check back soon!

RMS Average The root-mean-square (rms) average is another way of calculating a mean for a set of numbers. The rms average of a series of numbers is the square root of the arithmetic mean of the squares of the numbers:

$$

\text { rms average }=\sqrt{\frac{1}{N} \sum_{i=1}^N x_i^2}

$$

Write a MATLAB program that will accept an arbitrary number of positive input values and calculate the rms average of the numbers. Prompt the user for the number of values to be entered, and use a for loop to read in the numbers. Test your program by calculating the rms average of the four numbers 10,5 , 2 , and 5 .

Maxime Rossetti

Numerade Educator

Harmonic Mean The harmonic mean is yet another way of calculating a mean for a set of numbers. The harmonic mean of a set of numbers is given by the equation:

$$

\text { harmonic mean }=\frac{N}{\frac{1}{x_1}+\frac{1}{x_2}+\cdots+\frac{1}{x_n}}

$$

Write a MATLAB program that will read in an arbitrary number of positive input values and calculate the harmonic mean of the numbers. Use any method that you desire to read in the input values. Test your program by calculating the harmonic mean of the four numbers $10,5,2$, and 5 .

Rebecca Wickersham

Numerade Educator

Write a single program that calculates the arithmetic mean (average), rms average, geometric mean, and harmonic mean for a set of positive numbers. Use any method that you desire to read in the input values. Compare these values for each of the following sets of numbers:

(a) $5,5,5,5,5,5,5$

(b) $5,4,5,5,3,4,6$

(c) $5,1,5,8,4,1,8$

(d) $1,2,3,4,5,6,7$

Check back soon!

Mean Time between Failure Calculations The reliability of a piece of electronic equipment is usually measured in terms of Mean Time between Failures (MTBF), where MTBF is the average time that the piece of equipment can operate before a failure occurs in it. For large systems containing many pieces of electronic equipment, it is customary to determine the MTBFs of each component and to calculate the overall MTBF of the system from the failure rates of the individual components. If the system is structured like the one shown in Figure 5.20, every component must work in order for the whole system to work, and the overall system MTBF can be calculated as

$$

\mathrm{MTBF}_{\mathrm{s}, \mathrm{s}}=\frac{1}{\frac{1}{\mathrm{MTBF}_1}+\frac{1}{\mathrm{MTBF}_2}+\cdots+\frac{1}{\mathrm{MTBF}_{\mathrm{n}}}}

$$

Write a program that reads in the number of series components in a system and the MTBFs for each component and then calculates the overall MTBF for the system. To test your program, determine the MTBF for a radar system consisting of an antenna subsystem with an MTBF of 2000 hours, a transmitter with an MTBF of 800 hours, a receiver with an MTBF of 3000 hours, and a computer with an MTBF of 5000 hours.

( FIGURE CAN'T COPY )

Kari Hasz

Numerade Educator