Chapter 4
Chapter 4
Exercises
1) Write a for loop that will print the column of real numbers from 1.5 to 3.1 in
steps of 0.2.
2) Write a function sumsteps2 that calculates and returns the sum of 1 to n in steps
of 2, where n is an argument passed to the function. For example, if 11 is passed, it
will return 1 + 3 + 5 + 7 + 9 + 11. Do this using a for loop. Calling the function will
look like this:
>> sumsteps2(11)
ans =
36
sumsteps2.m
function outsum = sumsteps2(n)
% sum from 1 to n in steps of 2
% Format of call: sumsteps2(n)
% Returns 1 + 3 + ... + n
outsum = 0;
for i = 1:2:n
outsum = outsum + i;
end
end
3) Write a function prodby2 that will receive a value of a positive integer n and will
calculate and return the product of the odd integers from 1 to n (or from 1 to n1 if n
is even).
prodby2.m
function out = prodby2(n)
% Calculates and returns 1*3*5*..*n
% Format of call: prodby2(n)
% Returns product from 1 to n in steps of 2
out = 1;
for i = 1:2:n
out = out * i;
end
end
4) Prompt the user for an integer n and print “I love this stuff!” n times.
Ch4Ex4.m
% Prompts the user for an integer n and prints
% "I love this stuff" n times
5) In the Command Window, write a for loop that will iterate through the integers
from 32 to 255. For each, show the corresponding character from the character
encoding.
!
"
#
$
%
etc.
6) In the Command Window, write a for loop that will print the elements from a
vector variable in sentence format. For example, if this is the vector:
>> vec = [5.5 11 3.45];
this would be the result:
Element 1 is 5.50.
Element 2 is 11.00.
Element 3 is 3.45.
The for loop should work regardless of how many elements are in the vector.
Ch4Ex7.m
% Generate a random integer and loop to prompt the
% user for that many numbers and print the running sums
ranint = randi([2,5]);
runsum = 0;
for i = 1:ranint
num = input('Please enter a number: ');
runsum = runsum + num;
fprintf('The sum so far is %.1f\n', runsum)
end
There are many applications of signal processing. Voltages, currents, and sounds are
all examples of signals that are studied in a diverse range of disciplines such as
biomedical engineering, acoustics, and telecommunications. Sampling discrete data
points from a continous signal is an important concept.
8) A sound engineer has recorded a sound signal from a microphone. The sound
signal was “sampled,” meaning that values at discrete intervals were recorded
(rather than a continuous sound signal). The units of each data sample are volts.
The microphone was not on at all times, however, so the data samples which are
below a certain threshold are considered to be data values which were samples
when the microphone was not on, and therefore not valid data samples. The sound
engineer would like to know the average voltage of the sound signal.
Write a script that will ask the user for the threshold and the number of data
samples, and then for the individual data samples. The program will then print the
average and a count of the VALID data samples, or an error message if there were no
valid data samples. An example of what the input and output would look like in the
Command Window is shown below.
Note: In the absence of valid data samples, the program would print an error
message instead of the last line shown above.
Ch4Ex8.m
% Average valid data samples for a sound engineer
9) Write a script that will load data from a file into a matrix. Create the data file
first, and make sure that there is the same number of values on every line in the file
so that it can be loaded into a matrix. Using a for loop, it will then create as many
Figure Windows as there are rows in the matrix, and will plot the numbers from
each row in a separate Figure Window.
xfile.dat
4 9 22
30 18 4
Ch4Ex9.m
% load data from a file and plot data
% from each line in a separate Figure Window
load xfile.dat
[r c] = size(xfile);
for i = 1:r
figure(i)
plot(xfile(i,:),'k*')
end
10) A machine cuts N pieces of a pipe. After each cut, each piece of pipe is weighed
and its length is measured; these 2 values are then stored in a file called pipe.dat
(first the weight and then the length on each line of the file). Ignoring units, the
weight is supposed to be between 2.1 and 2.3, inclusive, and the length is supposed
to be between 10.3 and 10.4, inclusive. The following is just the beginning of what
will be a long script to work with these data. For now, the script will just count how
many rejects there are. A reject is any piece of pipe that has an invalid weight
and/or length. For a simple example ‐ if N is 3 (meaning three lines in the file) and
the file stores:
2.14 10.30
2.32 10.36
2.20 10.35
there is only one reject, the second one, as it weighs too much. The script would
print:
There were 1 rejects.
Ch4Ex10.m
% Counts pipe rejects. Ignoring units, each pipe should be
% between 2.1 and 2.3 in weight and between 10.3 and 10.4
% in length
for i=1:N
if weights(i) < 2.1 || weights(i) > 2.3 || ...
lengths(i) < 10.3 || lengths(i) > 10.4
count = count + 1;
end
end
fprintf('There were %d rejects.\n', count)
11) Improve the output from the previous problem. If there is only 1 reject, it
should print “There was 1 reject.”; otherwise for n rejects it should print “There
were n rejects.”
Ch4Ex11.m
% Counts pipe rejects. Ignoring units, each pipe should be
% between 2.1 and 2.3 in weight and between 10.3 and 10.4
% in length
for i=1:N
if weights(i) < 2.1 || weights(i) > 2.3 || ...
lengths(i) < 10.3 || lengths(i) > 10.4
count = count + 1;
end
end
if count == 1
fprintf('There was 1 reject.\n')
else
fprintf('There were %d rejects.\n', count)
end
12) When would it matter if a for loop contained for i = 1:4 vs.
for i = [3 5 2 6], and when would it not matter?
It would matter if the value of the loop variable was being used in the action of the
loop. It would not matter if the loop variable was just being used to count how
many times to execute the action of the loop.
13) Create a vector of 5 random integers, each in the range from ‐10 to 10. Perform
each of the following using loops (with if statements if necessary):
for i = 1:length(vec)
vec(i) -1
end
mysum = 0;
for i=1:length(vec)
if vec(i) > 0
mysum = mysum + 1;
end
end
mysum
for i = 1:length(vec)
abs(vec(i))
end
mymax = vec(1);
for i = 1:length(vec)
if vec(i) > mymax
mymax = vec(i);
end
end
mymax
14) Write a function that will receive a matrix as an input argument, and will
calculate and return the overall average of all numbers in the matrix. Use loops, not
built‐in functions, to calculate the average.
matave.m
function outave = matave(mat)
% Calculates the overall average of numbers in a matrix
% using the programming methods
% Format of call: matave(matrix)
% Returns the average of all elements
mysum = 0;
[r c] = size(mat);
for i = 1:r
for j = 1:c
mysum = mysum + mat(i,j);
end
end
outave = mysum/(r*c);
end
15) We have seen that by default, when using built‐in functions such as sum and
prod on matrices, MATLAB will perform the function on each column. A dimension
can also be specified when calling these functions. MATLAB refers to the columns as
dimension 1 and the rows as dimension 2, such as the following:
>> sum(mat,1)
>> sum(mat,2)
Create a matrix and find the product of each row and column using prod.
>> prod(mat)
ans =
55 240 80
>> prod(mat,2)
ans =
4224
250
16) Create a 3 x 5 matrix. Perform each of the following using loops (with if
statements if necessary):
Find the maximum value in each column.
Find the maximum value in each row.
Find the maximum value in the entire matrix.
Ch4Ex16.m
% Create a matrix, and use the programming methods to find
% the maximum in each row, and each column, and overall
% Maximum overall
mymax = mat(1,1);
for i = 1:r
for j = 1:c
if mat(i,j) > mymax
mymax = mat(i,j);
end
end
end
fprintf('The overall max is %.1f\n\n', mymax)
The outer loop must be over the rows if you want to perform an action for every
row; it must be over the columns if you want to perform an action for every column.
It does not matter if you simply need to refer to every element in the matrix.
18) Assume that you have a matrix of integers mat. Fill in the rest of the fprintf
statement so that this would print the product of every row in the matrix, in the
format:
The product of row 1 is 162
The product of row 2 is 320
etc.
Note: the value of col is not needed.
[row col] = size(mat);
for i = 1:row
fprintf('The product of row %d is %d\n', )
end
19) Write a script beautyofmath that produces the following output. The script
should iterate from 1 to 9 to produce the expressions on the left, perform the
specified operation to get the results shown on the right, and print exactly in the
format shown here.
>> beautyofmath
1 x 8 + 1 = 9
12 x 8 + 2 = 98
123 x 8 + 3 = 987
1234 x 8 + 4 = 9876
12345 x 8 + 5 = 98765
123456 x 8 + 6 = 987654
1234567 x 8 + 7 = 9876543
12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321
beautyofmath.m
% Shows the beauty of math!
leftnum = 0;
for i = 1:9
leftnum = leftnum * 10 + i;
result = leftnum * 8 + i;
fprintf('%d x 8 + %d = %d\n', leftnum, i, result)
end
20) Write a script that will print the following multiplication table:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
Ch4Ex20.m
% Prints a multiplication table
rows = 5;
for i = 1:rows
for j = 1:i
fprintf('%d ', i*j)
end
fprintf('\n')
end
21) The Wind Chill Factor (WCF) measures how cold it feels with a given air
temperature T (in degrees Fahrenheit) and wind speed V (in miles per hour). One
formula for WCF is
WCF = 35.7 + 0.6 T – 35.7 (V 0.16) + 0.43 T (V 0.16)
Write a function to receive the temperature and wind speed as input arguments, and
return the WCF. Using loops, print a table showing wind chill factors for
temperatures ranging from ‐20 to 55 in steps of 5, and wind speeds ranging from 0
to 55 in steps of 5. Call the function to calculate each wind chill factor.
Ch4Ex21.m
% Print table of wind chill factors
for t = -20:5:55
fprintf('%3d', t)
for v = 0:5:55
fprintf('%7.1f',wcf(t,v))
end
fprintf('\n')
end
wcf.m
function outwc = wcf(t, v)
% Calculates the wind chill factor
% Format of call: wcf(temperature, wind speed)
% Returns 35.74 + 0.6215T ? 35.75(V^0.16) + 0.4275T(V^0.16)
Ch4Ex22.m
% Print table of wind chill factors for temperatures
% ranging from -4 to 11F and wind speeds from 0 to 11mph
for t = -4:11
for v = 0:11
wcfmat(t+5,v+1) = wcf(5*t,5*v);
end
end
Ch4Ex23.m
% Approximates 1/e as (1-1/n)^n, and determines
% the value of n required for accuracy to 4 dec. places
actual = 1 / exp(1);
diff = 1;
n = 0;
If the variable x is initialized to have the value of 5 before the loop, what would
the action have to include in order for this to not be an infinite loop?
The action would have to increment the value of x, so that eventually it becomes
greater than or equal to 10.
25) Write a script that will prompt the user for the radius r and height of a cone,
error‐check the user’s input for the radius and the height, and then calculate and
print the volume of the cone (volume = Π/3 r2h).
Ch4Ex25.m
% Prompt the user for the radius & height of a cone
% and print the volume
26) Write a script (for example, called findmine) that will prompt the user for
minimum and maximum integers, and then another integer which is the user’s
choice in the range from the minimum to the maximum. The script will then
generate random integers in the range from the minimum to the maximum, until a
match for the user’s choice is generated. The script will print how many random
integers had to be generated until a match for the user’s choice was found. For
example, running this script might result in this output:
>> findmine
Please enter your minimum value: -2
Please enter your maximum value: 3
Now enter your choice in this range: 0
It took 3 tries to generate your number
Ch4Ex26.m
% Prompt the user for a range of integers and then an
% integer in this range. Generate random integer until
% user's is generated, counting how many tries it took.
27) Write a script that will prompt the user for N integers, and then write the
positive numbers (>= 0) to an ASCII file called pos.dat and the negative numbers to
an ASCII file called neg.dat. Error‐check to make sure that the user enters N
integers.
Ch4Ex27.m
% Prompt the user for N integers, writing the positive
% integers to one file and the negative integers to another
Ch4Ex28.m
% Calculates the Carnot efficiency, given the temperatures
% of cold and hot reservoirs, error-checking both
while Tc <= 0
Tc = input('Invalid! Enter the cold reservoir temperature: ');
end
while Th <= 0
Th = input('Invalid! Enter the hot reservoir temperature: ');
end
if Th < Tc
temp = Th;
Th = Tc;
Tc = temp;
end
29) Write a script that will continue prompting the user for positive numbers, and
storing them in a vector variable, until the user types in a negative number.
Ch4Ex29.m
% Prompt the user for positive numbers and store them
% in a vector until the user enters a negative number
uservals = [];
newval = input('Enter a positive number: ');
while (newval >= 0)
uservals = [uservals newval];
newval = input('Enter a positive number: ');
end
% display vector
uservals
30) Write a script echoletters that will prompt the user for letters of the alphabet
and echo‐print them until the user enters a character that is not a letter of the
alphabet. At that point, the script will print the nonletter, and a count of how many
letters were entered. Here are examples of running this script:
>> echoletters
Enter a letter: T
Thanks, you entered a T
Enter a letter: a
Thanks, you entered a a
Enter a letter: 8
8 is not a letter
You entered 2 letters
>> echoletters
Enter a letter: !
! is not a letter
You entered 0 letters
echoletters.m
% Echo print letters until the user enters a character
% that is not a letter of the alphabet
count = 0;
inchar = input('Enter a letter: ', 's');
31) Write a script that will use the menu function to present the user with choices
for functions “fix”, “floor”, and “ceil”. Error‐check by looping to display the menu
until the user pushes one of the buttons (an error could occur if the user clicks on
the “X” on the menu box rather than pushing one of the buttons). Then, generate a
random number and print the result of the user’s function choice of that number
(e.g. fix(5)).
Ch4Ex31.m
% Make the user choose a function 'fix', 'floor' or 'ceil'
% and print that function of a random number
x = rand*10;
switch choice
case 1
fprintf('sin(%.1f) is %.1f\n', x, fix(x))
case 2
fprintf('cos(%.1f) is %.1f\n', x, floor(x))
case 3
fprintf('tan(%.1f) is %.1f\n', x, ceil(x))
end
32) Write a script called prtemps that will prompt the user for a maximum Celsius
value in the range from ‐16 to 20; error‐check to make sure it’s in that range. Then,
print a table showing degrees Fahrenheit and degrees Celsius until this maximum is
reached. The first value that exceeds the maximum should not be printed. The table
should start at 0 degrees Fahrenheit, and increment by 5 degrees Fahrenheit until
the max (in Celsius) is reached. Both temperatures should be printed with a field
width of 6 and one decimal place. The formula is C = 5/9 (F‐32). For example, the
execution of the script might look like this (the format should be exactly like this):
>> prtemps
When prompted, enter a temp in degrees C in range -16
to 20.
Enter a maximum temp: 30
Error! Enter a maximum temp: 9
F C
0.0 -17.8
5.0 -15.0
.
.
.
40.0 4.4
45.0 7.2
Ch4Ex32.m
% Prompt for a maximum C temperature and print a table
% showing degrees C and degrees F
% Error-check
while maxtemp < -16 || maxtemp > 20
maxtemp = input('Error! Enter a maximum temp: ');
end
f = 0;
c = 5/9*(f-32);
33) Create an x vector that has integers 1 through 10, and set a y vector equal to x.
Plot this straight line. Now, add noise to the data points by creating a new y2 vector
that stores the values of y plus or minus 0.25. Plot the straight line and also these
noisy points.
Ch4Ex33.m
% Creates a straight line and also a "noisy" line
% by adding or subtracting 0.25 randomly from each point
x = 1:10;
y = x;
y2 = y;
plusMinus = [-1 1];
for i = 1:length(y2)
ran = randi([1:2]);
y2(i) = y2(i) + plusMinus(ran)*0.25;
end
plot(x,y,x,y2,'k*')
34) A blizzard is a massive snowstorm. Definitions vary, but for our purposes we
will assume that a blizzard is characterized by both winds of 30 mph or higher and
blowing snow that leads to visibility of 0.5 miles or less, sustained for at least four
hours. Data from a storm one day has been stored in a file stormtrack.dat. There are
24 lines in the file, one for each hour of the day. Each line in the file has the wind
speed and visibility at a location. Create a sample data file. Read this data from the
file and determine whether blizzard conditions were met during this day or not.
Ch4Ex34.m
% Reads wind and visibility data hourly from a file and
% determines whether or not blizzard conditions were met
load stormtrack.dat
winds = stormtrack(:,1);
visibs = stormtrack(:,2);
len = length(winds);
count = 0;
i = 0;
% Loop until blizzard condition found or all data
% has been read