Download presentation
Presentation is loading. Please wait.
Published bySolomon Phillips Modified over 9 years ago
1
MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014 www.clarkson.edu/class/honorsmatlab
2
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
3
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
4
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
5
For Loops – Basic Vocab For construction: Always contains for and end command Code is between the for and end for variable = parameters Code line 1; Code line 2;...“Loop Index” end
6
Sporadic For Loops For a preset vector of variables for x = [1,3,13,90] value = 2*x^2; disp(value); end Output: 2 18 338 16200
7
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
8
But…….. What if you want to store some values in an array to access later in the program after the loop is complete?
9
Loops – Defining an Array You must index your array for ii = 1:5 a(ii) = 4*ii; disp(a); end a is redefined each time (“iteration”) through the loop Output 4 4 8 4 8 12 4 8 12 16 4 8 12 16 20 When your loop is done you have: a = [4 8 12 16 20]
10
Nested logicals in For Loops You can have logical statements in loops count = 0; for ii = [35 48 56 42 47 59]; grade = ii./60.*100; if grade >= 90 count = count + 1; end disp([‘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
11
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
12
For Loops with Arrays You can execute arrays in loops MatLab 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
13
Nesting Loops You can put one loop inside of another! Make sure you use different loop indexes ExampleMeaning: disp('# *# =#'); for ii = 1:3 1 * 1 = 1 for jj = 1:3 1 * 2 = 2 product = ii * jj; 1 * 3 = 3 disp([num2str([ii jj product])]); 2 * 1 = 2 end 2 * 2 = 4 end 2 * 3 = 6 Ends the inner most loop3 * 1 = 1 Ends the outer loop3 * 2 = 6 3 * 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.
14
While Loops - Basic While construction: Always contains while and end command Code is between the while and end while logical_expression Code line 1; Code line 2;... end Logical Examples (Two weeks ago): x >= 5, x 5, x==1 || x==10
15
While Loops Concept similar to for loops m = 0; while (m < 5) m = m + 1; disp(m); end Output 1 2 3 4 5
16
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
17
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 fprintf(‘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.
18
Break and Continue Break: Can be used to stop a loop % This program accepts 10 positive input values n = 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.
19
Another Example Guess Joe’s favorite number in 5 guesses guess = 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
20
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:100 square(ii) = ii^2; end Rather than this: for ii = 1:100 square(ii) = ii^2; end
21
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
22
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!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.