Exercises
Please complete each exercise or answer the question before reviewing the posted solution comments.
-
Write a
forloop to display N asterisks (*), one on each line, where N is a number given at the beginning of your script. For example, if N is 5, your script should print out:* * * * *
This
forloop will display N asterisks on N different lines. Compare this with thewhileloop that solves the same problem.for n = 1 : N disp('*'); end -
Write a
forloop to display N asterisks (*) on one line. Assume that N has already been assigned a number. If N is greater than 80, display only 80 asterisks. If N is less than 1, display no asterisks.For example, if N is 5, your script should print out
*****
Here is a fragment that will work if N has previously had its value assigned. Notice how the variable
starlinewith N asterisks is created in the loop and it is printed after the loop ends. This is because thedisp()command prints a new line after its argument.if N > 80 N = 80; end starline = ''; for n = 1 : N starline = [starline '*']; end disp(starline);
Once again, the
forloop is quite convenient syntax for count-controlled loops such as this. -
Write a code fragment that uses a
forloop to repeatedly prompt the user for positive integer or zero. As long as negative values or non-integers are entered, your loop should ask the user for a positive integer.Here is a script that will work but has undesireable properties as described following the code.
val = -1; for n = 1 : 100000; val = input('Enter a positive integer or zero: '); if val >= 0 & rem(val,1) == 0 break; % break out of the loop when a valid value is found end endThe use of
breakstatements is generally discouraged due to the increased difficulty in following the control flow of programs that usebreakstatements. Such loops have two (or more) ways to exit or stop the loop, this makes them harder to debug than loops that have only one exit point.Also, the use of the value
100000or other similarily large value is logically incorrect and this also makes the code harder to maintain. We really don't want this loop to execute a large number or infinite number of times only until the user enters a valid value. Iteration that should repeat until a condition is met (or while a bad condition exists) should be implemented with awhileloop as shown here:val = -1; while val < 0 | rem(val,1) ~= 0 val = input('Enter a positive integer or zero: '); end -
Write a
forloop that counts the number of values in a vector that are equal to some number N and displays that value in a user-friendly way. (Hint: Usedispto include text and values.) Assume that the vector is saved asvaluesand thatNhas already been assigned.This fragment assumes that
Nandvalueshave already been assigned. This could be the case if the fragment was in the body of a function or nested inside of some other code fragment.K = length(values); % index of last value to check count = 0; % initialize a counter variable for k = 1 : K if values(k) == N count = count + 1; end end disp(['There are ', num2str(count), ' values of ', num2str(N),' in the vector ']); -
Write a script that uses a
forloop to compute and plot the finite Fourier series given by the sum:
over the interval
x=(0,8. The plot you should see is called the 'sawtooth function'.
)Here's one algorithm (set of steps) for solving this problem with iteration (loops):
- Create a vector with many
xvalues in the range (to plot a continuous curve). - Create a vector of
yvalues with the initial value of 0 that correspond to thexvector created. - For each value n from 1 to 1000
- Replace each value in
ywith the calculated valuey + sin(n*x)/n.
- Replace each value in
- Plot
xvsyand label the axis.
% one way to plot the sawtooth using a for loop clear; x=[0:0.1:8] * pi; % range from 0 to 8pi with last entry actually 8pi y = 0*x; % total starts at 0 for each value of x % creates a vector with the same number of values as in x, % but each value is 0 % Compute the fournier series for each value of x for n = 1:1000 y = y + sin(n*x)/n; % do not need element-wise operators here end % because n is a scalar (inside the loop) plot(x,y); axis([x(1) x(length(x)), -pi/2, pi/2]) title('first method') - Create a vector with many
-
Write a script that implements this algorithm to plot the finite Fourier series given above:
- Create a vector of the
nvalues from 1 to 1000. - Initialize an index variable
ito 1. This value indicates which index inyto store the calculate value. - For each value x from 1 to 8
- Calculate the value
sum(sin(n*x)./n)to put the sum of allsin(n*x)./nvalues and store the sum in positioniofy - Increment the index
ivalue for the next iteration.
- Calculate the value
- Plot
xvsyand label the axis.
% a second iterative way to plot the sawtooth function clear; figure; n = 1:1000; i=1; % initialize the index to the first index of y for x = [0:0.1:8] * pi y(i) = sum(sin(n*x)./n); % need element-wise division, n is a vector here % save value in position i of y i = i + 1; % update the index for the next iteration end x = [0:0.1:8] * pi plot(x,y); axis([x(1) x(length(x)), -pi/2, pi/2]) title('second method') - Create a vector of the