Question on the file
EMEC 202
Spring 2019
PRE5 - Topic 5 lab
Loops
EMEC 203-CAE II
Fall 2018
PRE5 - Topic 5 Prelab
Loops
SELF-GUIDED LEARNING:
This topic covers the basic control flow structures like for loops and while loops. These will make if statements much more useful. This is one of the most important topics of the semester.
for Loops:
2. Write out the general form of a for Loop.
3. Given the following vectorized code:
>> x=[1:10];
>> f=x.^2+2;
Rewrite this code using a for loop that defines each element of f one at a time. Make sure to preallocate memory to f before filling each spot.
4. See the following code. Remove repetition by generalizing the code with a loop. Reduce the code to <10 lines of code. This code is posted to D2L if you’d like to run it.
5. See the following code. Rewrite the code in one line using the find function.
x=[-1 3 7 2 4 0];
v=[];
for i=1:length(x)
if x(i)<=2
v=[v, x(i)];
end
end
while Loops:
6. Define a while Loop.
7. Write out the general form of a while Loop.
8. Rewrite the code in #3 with a while loop instead of a for loop.
9. Read the code below and determine what the result will be before typing it into MATLAB and checking show results below.
count=0;
number=8;
while number > 3
number = number-2;
fprintf('number is %d\n', number)
count=count+1;
end
fprintf('count is %d\n', count)
Name:_________________________________