MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .
-
Upload
solomon-phillips -
Category
Documents
-
view
239 -
download
0
Transcript of MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .
MATLAB FUNDAMENTALS:CONTROL STRUCTURES – LOOPS
HP 100 – MATLABWednesday, 10/1/2014
www.clarkson.edu/class/honorsmatlab
Quote and Video…
“Check Blackboard for the new homework. I know none of you will, but it makes me feel better.”
Sumona Mundal Statistics
Video: https://www.youtube.com/watch?
v=bhcA4Ry65FU
Introduction to Loops
Loops: Simply a way for a program to execute certain values for a function In other words, repeat a section of
code Can be a pattern or sporadic Used when vectorization is not
possible or impractical We will learn for and while loops
Loops
MATLAB construct which allows multiple executions of the same block of code multiple times. The while loop is repeated an indefinite number of times until a logical
expression (like we learned a week ago) is satisfied The for loop is repeated a predefined number of times Visualize:
While Loop For Loop
Statement = true
Repeat 3 times
For Loops – Basic Vocab
For construction: Always contains for and end
command Code is between the for and end
for variable = parametersCode line 1;
Code line 2;
. . . “Loop Index”
end
Sporadic For Loops
For a preset vector of variablesfor x = [1,3,13,90]
value = 2*x^2;disp(value);
end
Output: 2 18 33816200
Simple Vector Loops
When your variables are in a pattern:factorial = 1;for ii = 1:5
factorial = factorial * ii; fprintf(‘%5.0f \n’, factorial);end
Output:1
2 6
. 24 120
But……..
What if you want to store some values in an array to access later in the program after the loop is complete?
Loops – Defining an Array
You must index your arrayfor ii = 1:5
a(ii) = 4*ii;disp(a);
end
a is redefined each time (“iteration”) through the loop
Output44 84 8 124 8 12 164 8 12 16 20
When your loop is done you have: a = [4 8 12 16 20]
Nested logicals in For Loops
You can have logical statements in loopscount = 0;for ii = [35 48 56 42 47 59];
grade = ii./60.*100;if grade >= 90
count = count + 1;end
enddisp([‘In this group, ’ num2str(count) ‘ students got an A on the first physics exam!’]);
Output In this group, 2 students got an A on the first physics exam
Incremental For Loops
You can have loops in increments for a = start:incr:end
Expression 1 Expression 2 ... Expression n
end
Just be careful with your vectors. MATLAB will automatically fill empty slots in your vector with zeros
For Loops with Arrays
You can execute arrays in loopsMatLab uses each column for each iteration format bank for ii = [1 2 3; 4 5 6; 7 8 9]; transpose = ii’; disp(transpose);
end Output 1.00 4.00 7.00 2.00 5.00 8.00 3.00 6.00 9.00
Nesting Loops
You can put one loop inside of another! Make sure you use different loop indexes Example Meaning:disp('# *# =#');for ii = 1:3 1 * 1 = 1
for jj = 1:3 1 * 2 = 2product = ii * jj; 1 * 3 = 3disp([num2str([ii jj product])]); 2 * 1 = 2
end 2 * 2 = 4end 2 * 3 = 6
Ends the inner most loop 3 * 1 = 1Ends the outer loop
3 * 2 = 63 * 3 = 9
Remember: The end’s will close the innermost loop first and work out Any “ break ” or “ continue ” will also refer to the innermost loop which
contains it – we’ll discuss this more later.
While Loops - Basic
While construction: Always contains while and end command Code is between the while and end
while logical_expressionCode line 1;
Code line 2;
. . .
end Logical Examples (Two weeks ago):x >= 5, x<10 && x>5, x==1 || x==10
While Loops
Concept similar to for loops m = 0; while (m < 5) m = m + 1;
disp(m);
end Output 1 2 3 4 5
Indexed Arrays
Like for loops, can store value as an indexed array m = 0; while(m < 4) m = m + 1;
array(m) = m^2; end
disp(array); Output 1 4 9 16
Useful when you don’t know how many iterations (“cycles”) you will
need to complete
The Physics Example – Again! While Construct:
scores = [35 48 56 42 47 59];student = 0;count = 0;while count < length(scores);
count = count + 1; grade = scores(count) / 60 * 100; if grade >= 90
student = student + 1;end
endfprintf(‘In this group, %1.0f students got an A on the first physics exam \n’, student);
Output In this group, 2 students got an A on the first physics exam.
Break and Continue
Break: Can be used to stop a loop% This program accepts 10 positive input valuesn = 0;while n < 10; n = n + 1;
a = input(‘Enter a positive number ’); if a < 0
disp(‘Has to be positive. You broke it! ’); break end
disp(n)end
Output: Program displays all positive numbers until a negative number was entered.
Another Example
Guess Joe’s favorite number in 5 guessesguess = 0;while guess < 5;
guess = guess + 1; fprintf(‘\nThis is guess number %1.0f \n’,guess); a = input(‘Make a guess! ’); if a == 8
disp(‘You guessed it! ’); break
else disp(‘Nope. Try again.’); continue end
end
Good Programming Practice:
Indent the bodies of loops Not necessary but you should always do it. To make
your code pretty, highlight all code, right click, smart indent
Never modify your loop index within the loop. You will produce errors that you will never find!
Preallocate all arrays before using them in a loop. Your code will run much faster! Do this:
square = zeros(1,100);for ii = 1:100square(ii) = ii^2;
end
Rather than this:
for ii = 1:100
square(ii) = ii^2;
end
The for Loop - Vecotorization (cont.)
Good Programming Practice: Vectorize your code when you can.
To perform the same calculations a vectorized code can perform 15 times faster than code using loops.
Ex: Using a Loop Vecotrized for ii = 1:100 ii = 1:100; square(ii) = ii^2; square = ii.^2 square_root(ii) = ii^(1/2); square_root(ii)=
ii.^(1/2); cube_root(ii) = ii^(1/3); cube_root(ii) =
ii.^(1/3) end