0% found this document useful (0 votes)
234 views19 pages

Chapter 4: Loop Statements Exercises: Sumsteps2

The document provides 15 exercises involving the use of for loops in MATLAB. Some key examples include: 1) Writing a for loop to print real numbers from 1.5 to 3.1 in steps of 0.2. 2) Writing a function to calculate and return the sum of integers from 1 to n in steps of 2, using a for loop. 3) Writing a function to calculate and return the product of odd integers from 1 to a given integer n, using a for loop. 4) Prompting the user for an integer n and printing a string n times using a for loop. 5) Writing a for loop to iterate through character codes from 32 to 255 and
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
234 views19 pages

Chapter 4: Loop Statements Exercises: Sumsteps2

The document provides 15 exercises involving the use of for loops in MATLAB. Some key examples include: 1) Writing a for loop to print real numbers from 1.5 to 3.1 in steps of 0.2. 2) Writing a function to calculate and return the sum of integers from 1 to n in steps of 2, using a for loop. 3) Writing a function to calculate and return the product of odd integers from 1 to a given integer n, using a for loop. 4) Prompting the user for an integer n and printing a string n times using a for loop. 5) Writing a for loop to iterate through character codes from 32 to 255 and
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Chapter 4: Loop Statements

 
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 n­1 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

n = input('Enter an integer: ');


for i = 1:n
disp('I love this stuff!')
end
 
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.  
 
>> for i = 32:255
disp(char(i))
end
  
!
"
#
$
%
 
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. 
 
>> 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

Please enter a data sample: 0.4


Please enter a data sample: 5.5
Please enter a data sample: 5.0
Please enter a data sample: 2.1
Please enter a data sample: 6.2
Please enter a data sample: 0.3
Please enter a data sample: 5.4

The average of the 4 valid data samples is 5.53 volts.


 
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

disp('Please enter the threshold below which samples will be')


thresh = input('considered to be invalid: ');
numsamp = input('Please enter the number of data samples to be
entered: ');
mysum = 0;
mycount = 0;
for i=1:numsamp
datasamp = input('\nPlease enter a data sample: ');
if datasamp >= thresh
mysum = mysum + datasamp;
mycount = mycount + 1;
end
end
if mycount > 0
fprintf('\nThe average of the %d valid data samples is %.2f
volts.\n',...
mycount,mysum/mycount)
else
fprintf('There were no valid data samples.\n')
end
 
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

% read the pipe data and separate into vectors


load pipe.dat
weights = pipe(:,1);
lengths = pipe(:,2);
N = length(weights);

% the programming method of counting


count = 0;

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

% read the pipe data and separate into vectors


load pipe.dat
weights = pipe(:,1);
lengths = pipe(:,2);
N = length(weights);

% the programming method of counting


count = 0;

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

mat = randi([1, 30], 3,5)


[r c] = size(mat);

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

% Maximum for each row


for i = 1:r
mymax = mat(i,1);
for j = 1:c
if mat(i,j) > mymax
mymax = mat(i,j);
end
end
fprintf('The max of row %d is %.1f\n', i, mymax)
end
fprintf('\n')

% Maximum for each column


for j = 1:c
mymax = mat(1,j);
for i = 1:r
if mat(i,j) > mymax
mymax = mat(i,j);
end
end
fprintf('The max of col %d is %.1f\n', j, mymax)
end
 
17) With a matrix, when would: 
 your outer loop be over the rows 
 your outer loop be over the columns 
 it not matter which is the outer and which is the inner loop? 
 
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
 
 
fprintf('The product of row %d is %d\n', i, prod(mat(i,:)))
 
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

% Print column headers


fprintf('%45s\n ', 'Wind Speeds')
for v = 0:5:55
fprintf('%7d', v)
end
fprintf('\nTemp\n')

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)

outwc = 35.74 + 0.6215 .* t - 35.75 .* (v.^0.16) + ...


0.4275 .* t .* (v.^0.16);
end
 
22) Instead of printing the WCFs in the previous problem, create a matrix of  WCFs 
and write them to a file. 
 
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

save wcfs.dat wcfmat -ascii


 
23) The inverse of the mathematical constant e can be approximated as follows:  
n
1  1
 1    
e  n
Write a script that will loop through values of n until the difference between the 
approximation and the actual value is less than 0.0001. The script should then print 
out the built‐in value of e‐1 and the approximation to 4 decimal places, and also print 
the value of n required for such accuracy. 
 
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;

while diff >= 0.0001


n = n + 1;
approx = (1 - 1/n)^n;
diff = actual - approx;
end

fprintf('The built-in value of 1/e is %.4f\n',actual)


fprintf('The approximation is %.4f\n',approx)
fprintf('The value of n is %d\n',n)
 
24) Given the following loop: 
while x < 10
action
end
 For what values of the variable x would the action of the loop be skipped entirely? 
 
The action would be skipped entirely if x is greater than or equal to 10 to begin with. 
 
 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

% Error-check the user's inputs


rad = input('Enter the radius of the cone: ');
while (rad <=0)
fprintf('Error! Please enter a valid radius.\n')
rad = input('Enter the radius of the cone: ');
end
ht = input('Enter the height of the cone: ');
while (ht <=0)
fprintf('Error! Please enter a valid height.\n')
ht = input('Enter the height of the cone: ');
end

fprintf('The vol is %.2f\n',(pi/3)*rad*rad*ht);


 
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.

mymin = input('Please enter your minimum value: ');


mymax = input('Please enter your maximum value: ');
mychc = input('Now enter your choice in this range: ');
counter = 1;

myran = randi([mymin, mymax]);


while (myran ~= mychc)
myran = randi( [mymin, mymax]);
counter = counter + 1;
end
fprintf('It took %d tries to generate your number\n',counter)
 
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

% initialize vectors to store pos and neg integers


posints = [];
negints = [];
% loop n times
n=10;
for i=1:n
inputnum = input('Enter an integer: ');
num2 = int32(inputnum);
% error check to make sure integers are entered
while num2 ~= inputnum
inputnum = input('Invalid! Enter an integer: ');
num2 = int32(inputnum);
end
% add to appropriate vector
if inputnum < 0
negints = [negints inputnum];
else
posints = [posints inputnum];
end
end

% write vectors to files


save pos.dat posints -ascii
save neg.dat negints -ascii
 

28) In thermodynamics, the Carnot efficiency is the maximum possible efficiency of a


heat engine operating between two reservoirs at different temperatures. The Carnot
efficiency is given as
TC
 1
TH
where TC and TH are the absolute temperatures at the cold and hot reservoirs,
respectively. Write a script that will prompt the user for the two reservoir temperatures in
Kelvin and print the corresponding Carnot efficiency to 3 decimal places. The script
should error-check the user’s input since absolute temperature cannot be less than or
equal to zero. The script should also swap the temperature values if TH is less than TC .
 
Ch4Ex28.m 
% Calculates the Carnot efficiency, given the temperatures
% of cold and hot reservoirs, error-checking both

Tc = input('Enter the cold reservoir temperature: ');

while Tc <= 0
Tc = input('Invalid! Enter the cold reservoir temperature: ');
end

Th = input('Enter the hot reservoir temperature: ');

while Th <= 0
Th = input('Invalid! Enter the hot reservoir temperature: ');
end

if Th < Tc
temp = Th;
Th = Tc;
Tc = temp;
end

carnotEff = 1 - (Tc / Th);


fprintf('The Carnot efficiency is %.3f\n',carnotEff)
 
 
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
 
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');

%OR: while isletter(inchar)


while (inchar >='a' && inchar <='z') || ...
(inchar >='A' && inchar <='Z')
fprintf('Thanks, you entered a %c\n', inchar)
count = count + 1;
inchar = input('Enter a letter: ', 's');
end
fprintf('%c is not a letter\n', inchar)
fprintf('You entered %d letters\n', count)
 
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

choice = menu('Choose a function','fix','floor','ceil');


while (choice < 1 || choice > 3)
fprintf('Error; please choose a function!\n')
choice = menu('Choose a function','fix','floor','ceil');
end

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

fprintf('When prompted, enter a temp in degrees C in')


fprintf(' range -16\n to 20.\n')
maxtemp = input('Enter a maximum temp: ');

% Error-check
while maxtemp < -16 || maxtemp > 20
maxtemp = input('Error! Enter a maximum temp: ');
end

% Print table include headers


fprintf(' F C\n');

f = 0;
c = 5/9*(f-32);

while (c <= maxtemp)


fprintf('%6.1f %6.1f\n',f,c)
f = f + 5;
c = 5/9*(f-32);
end

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

while count < 4 && i < len


i = i + 1;
if winds(i) >= 30 && visibs(i) <= .5
count = count + 1;
else
count = 0;
end
end
if count == 4
fprintf('Blizzard conditions met\n')
else
fprintf('No blizzard this time!\n')
end
 

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy