ENGR 17
A6 Loops
Due: next Tuesday
Create folder A6 and set your workspace to it. Do any 2 for 10 points. If one of those two is #3 you'll get a
point of extra credit.
1) This problem will give us a chance to practice using loops to solve problems that can also be solved using
the vector operators we've practiced with before.
First we'll solve this problem with a loop. To do this, create a script called minDistA.m.
After adding the usual comment heading with the program name and your name in it, let's think this through
before starting. Notice since we are not asked to plot anything we don't really have to compute vectors for x
and y. We just want to find the time of closest approach to the origin, and the corresponding distance.
Although several possibilities exist, we can try a minimalist approach here. For example we might:
1) create a variable minD = 10000 (really big value bigger than any possible distance), and minT = 0 (time
of closest approach). these are the initial settings for our min calculation as we demonstrated in
LoopDemos.m
2) make a for loop for t going from 0 to 4 in steps of 0.01
(remember, t will be a scalar, it will only hold one of these values at a time)
a. inside the loop, for every value of t we will calculate x and y, ( also scalar values)
b. calculate distance using the sqrt function
c. if the distance is smaller than minD
i. set minD to the current value of distance
ii. set minT to the current value of t
That's it! When this program finishes the value of minD and minT should be printed out. Copy these values
into your script and comment them out.
Now, to check your work create a new script, minDistB.m. Here we'll go back to using vectors to solve our
problem. Here is an outline of how that might work:
1) create a vector of t from 0 to 4 in steps of 0.01 (now a VECTOR)
2) create x and y vectors using vector math
3) create distance vector using vector math
4) find the minD and minT using the min function operating on the distance vector. Copy your answer
into your script and comment it out.
Make sure your answers for both parts agree before continuing. Also, create a plot of the trajectory (y vs x)
and make sure the picture supports your answers as well.
2) The Ulam Sequence
A mathematician named Ulam proposed generating a sequence of numbers from any positive integer n (n > 0)
as follows:
If n is 1, stop.
If n is even, the next number is n/2.
If n is odd, the next number is 3*n + 1.
Continue with this process until reaching 1.
Here are some examples for the first few integers.
2
3
4
5
6
7
-> 1
-> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
-> 2 -> 1
-> 16 -> 8 -> 4 -> 2 -> 1
-> 3 -> etc as for 3 above.
-> 22 -> 11 -> 34 -> 17 -> 52 -> 26 -> 13 -> 40 -> 20 -> 10 -> 5 -> see 5 above
The Ulam sequence is interesting because it always seems to reach 1 (although that can't be proved) and the
length of any sequence is unpredictable.
In this problem we are going to use loops to help us make a plot of the length of Ulam sequence as n goes
from 1 to 1000.
To begin, we'll need to construct the Ulum function. Start a function file ulam.m with the normal comments.
We will invoke ulam by the expression u = ulam(n) where u is a vector (the sequence) and n is a scalar (the
starting value of the sequence) so our first line will read:
function u = ulam( n )
we'll begin this function by putting n in the first cell of vector u:
u(1) = n;
we'll also create a variable k to keep track of which cell in the output vector u we are computing, and note that
we start k at 1 meaning we have just computed u(1):
k = 1;
Then we'll create a while loop with the conditon to repeat being that u(k) is not equal to 1 because when we
get a value of 1 that is the end of the Ulam sequence.
while u(k) ~= 1
Our next step is to calculate the next value of vector u, that is, u(k+1), based on whether u(k) is even or odd.
Note that we can check if u(k) is even using rem( u(k) ,2) this function will produce a 0 for even number
(remainder of u(k)/2 is 0 when u(k) is even)
The calculation of the new value, u(k+1) will look something like this (you'll need the if statement mentioned
above to select the appropriate statement):
u(k+1) = 3*u(k) + 1;
u(k+1) = u(k)/2;
% for the case when u(k) is odd
% for the case when u(k) is even
After calculating the new value, u(k+1), then add one to k for the next cycle. That's it! End the loop, which will
also end the function definition.
Test your function on the command line using a few values from the examples above. For example, typing
ulam(2) should give you a vector with a single value, 1, while ulam(3) will give you a vector
[ 10 5 16 8 4 2 1 ].
See the other examples above for more test cases.
Once this works we can begin to construct the plot of Ulam sequence lengths. To do this, we'll make a new
script called ulamPlot.m
This script will need to create a vector of input values and ulam lengths so it can construct the required plot.
However, the ulam function is not "vectorized", it works on only scalar data. Therefore, we must use a for
loop to feed scalar values one at a time into ulam, then store the resulting sequence lengths in a vector for
plotting when the loop is finished.
To being, let's create the ulamCount vector:
ulamCount = zeros(1,1000); % a blank vector already sized correctly will speed matlab's computation
now lets start a for loop to step over all the n values we want to test.
for n = 1:1000
inside the loop for each value of n you'll want to
a) compute the length of ulam(n) and store that in ulamCount(n)
Once the loop finishes, you can simply plot(ulamCount ) to see what it looks like. Save the plot as
ulamPlot.jpg
Using the max function find the maximum value of ulamCount and the corresponding n that produced it. Put
your answers for these inside comments in ulamCount.m
3) Tracing. Download trace.m from the website. For the following loops, complete the trace tables inside
that file to determine the result each loop creates. Do not copy/run these lines in a script. Instead, use your
understanding of how loops run to predict what the computer would do. You can consider these practice
questions for Test 2.
A) x = zeros(1,5)
for k=1:5
x(k+1) = x(k) * 2
end
disp('x = ');
x
B) x = 5;
k = 0;
while x < 25
k = k + 1;
y(k) = 3*x;
x = 2*x-1;
end
disp('y = ');
y
C)
k= 1; b= -2; x= -1; y = -2;
while k <=3
y = x^2 – 3;
if y < b
b=y;
end
x = x + 1;
k=k+1
end
fprintf('after loop, k = %d \n', k);
fprintf('x = %d \n', x);
D)
for k = 1:8
if k<4
x(k)=2*k;
else
x(k)= x(k-1) – 3;
end
end
disp('x = ');
x
4) Challenge: find the number of TV sets, Steros, and Speakers the company should make to maximize profits.
Some thoughts that can help you work through this problem:
1) Based on our inventory, what is the max number of TVs we could make if we used all our inventory for
TVs? What about Stereos and Speakers? Can you figure out how to use matlab vector operations to
tell us these values? For example if inventory = [450 250 800 450 600]; and TV = [1 1 2 1 2]; how can
we find the maxTV value?
2) To test every possible combination, you'll want to set up a series of 3 nested for loops, one for numTV,
one for numStero, one for numSpeaker. The first loop will look something like:
for numTV = 0:maxTV
3) Suppose inside the innermost loop we construct a "permutation vector"
p = [ numTV numStereo numSpkr];
That is, a specific selection of a certain number of TVs, Stereos and Speakers from all possibile
permutations. Suppose we also have a vector
unit_profit = [80 50 40];
The profit we would make from such a permutation could then be calculated using vector math.
4) Each time through the loop we'll want to
a. construct the permutation vector
b. compute the permutation profit
c. check if we have sufficient inventory to produce that permutation
(remember if we compare two vectors using <, all cells must meet criteria for true)
d. if we do have enough inventory,
i. check if the current profit is greater than the max we've seen so far
ii. if that's true, then remember this profit and the permutation that created it
© Copyright 2025 Paperzz