Top Banner
MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 www.clarkson.edu/class/honorsmatlab
22

MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

Dec 31, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 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

Page 2: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 3: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 4: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 5: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 6: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 7: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 8: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

But……..

What if you want to store some values in an array to access later in the program after the loop is complete?

Page 9: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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]

Page 10: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 11: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 12: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 13: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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.

Page 14: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 15: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

While Loops

Concept similar to for loops m = 0; while (m < 5) m = m + 1;

disp(m);

end Output 1 2 3 4 5

Page 16: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 17: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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.

Page 18: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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.

Page 19: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 20: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 21: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

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

Page 22: MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 .

Questions and Homework:

Questions?

Homework: 8.9, 8.23, 8.24, 8.25 (with plot)

Due next Wednesday at 5 (like normal). Get started early!