Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Programming in MATLAB

Similar presentations


Presentation on theme: "Introduction to Programming in MATLAB"— Presentation transcript:

1 Introduction to Programming in MATLAB
Intro. MATLAB Peer Instruction Lecture Slides by Dr. Cynthia Lee, UCSD is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. Based on a work at 

2 LOOPS: Examples

3 Fill in the blank in the following code to create an infinite loop
Fill in the blank in the following code to create an infinite loop. Do no not add or change code except adding one line of code on the blank line. D – both B and C would not work because inf is actually larger than 10, so it would end the loop after the first iteration. Resets the counter to 1 each time, so the counter is 2 every time it checks the loop condition, and 2 <= 10 is true. Loop variable cannot make progress towards 10 and loop will run forever. Resets the counter to 0 each time, so the counter is 1 every time it checks the loop condition, and 1 <= 10 is true. Loop variable cannot make progress towards 10 and loop will run forever. counter = inf; % MATLAB built-in value “inf” counter = 1; counter = counter – 1; Other/none/more than one

4 Write a loop that counts how many pure blue ([0 255 0]) pixels are in an image.
function [blues] = CountBluePixels(im) for row = for col = pix = im(row,col,:); end

5 How many times is “CSE 7” printed when this code runs?
Other/none/more than one C 1st time through alpha = 1, so the for loop iterates 1:1 or just one time. 2nd time through alpha = 4, so the for loop iterates 1:4 or 4 times. To conclude this iteration, alpha = gives 7, so the while loop condition will fail. That is a total of 5 times.

6 What is the value of alpha after this code runs?
4 5 7 10 Other/none/more than one C See explanation on last slide.

7 Write a loop that finds the average amount of red in an image.
function [ave] = AverageRed(im) for row = for col = red = im(row,col,1); end

8 How many times does ‘hi’ print?
row = 1; while row <= 2 for col = 1:10 display(‘hi’) row = row + 1; end 2 10 20 Keeps printing ‘hi’ forever in an infinite loop C 1 <= 2, so the while loop body executes. The for loop will execute 10 times as usual. This adds 1 to row 10 times, in other words adding 10 to row in total, giving row = 11. Then we add one to row at the end of the while loop, giving row = <= 2 is false, so the while loop terminates. We have printed hi just the 10 times.


Download ppt "Introduction to Programming in MATLAB"

Similar presentations


Ads by Google