Chapter 4: Loop Statements Exercises: Sumsteps2
Chapter 4: Loop Statements Exercises: Sumsteps2
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.
for i = 1.5: 0.2: 3.1
disp(i)
end
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
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.
>> vec = [44 11 2 9 6];
>> for i = 1:length(vec)
fprintf('Element %d is %.2f\n',i,vec(i))
end
Element 1 is 44.00
Element 2 is 11.00
Element 3 is 2.00
Element 4 is 9.00
Element 5 is 6.00
7) Write a script that will:
generate a random integer in the range from 2 to 5
loop that many times to
o prompt the user for a number
o print the sum of the numbers entered so far with one decimal place
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.
Please enter the threshold below which samples will be
considered to be invalid: 3.0
Please enter the number of data samples to enter: 7
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):
>> vec = randi([-10, 10], 1, 5)
subtract 3 from each element
for i = 1:length(vec)
vec(i) -1
end
count how many are positive
mysum = 0;
for i=1:length(vec)
if vec(i) > 0
mysum = mysum + 1;
end
end
mysum
get the absolute value of each element
for i = 1:length(vec)
abs(vec(i))
end
find the maximum
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.
>> mat = randi([1, 30], 2,3)
mat =
11 24 16
5 10 5
>> 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)
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)
for t = -4:11
for v = 0:11
wcfmat(t+5,v+1) = wcf(5*t,5*v);
end
end
actual = 1 / exp(1);
diff = 1;
n = 0;
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
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
The format must be exactly as shown above.
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');
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