Introduction to Programming in MATLAB Intro MATLAB Peer
Introduction to Programming in MATLAB Intro. MATLAB Peer Instruction Lecture Slides by Dr. Cynthia Lee, UCSD is licensed under a Creative Commons Attribution-Non. Commercial-Share. Alike 3. 0 Unported License. Based on a work at www. peerinstruction 4 cs. org. 1
for loops • Think about possible drawbacks of using for loops for an action that you want to repeat many, many times is. For example, let’s say you want to add up all the numbers from 1 to 100, 000 and you write this loop to do it: sum = 0; for num = 1: 100000 sum = sum + num; end • What is one drawback of doing the calculation this way? a) b) c) d) It might take so long to calculate that it will forget the sum and come up with the wrong answer MATLAB actually makes a vector with size 100000 to hold all the values of num that will be used, and this takes up a huge amount of space in the computer’s memory It might take so long to calculate that it will never finish Other 2
for loops im = imread(‘blacklab. jpg’); for row = [2 66 101 11 43 35 85 170] im(row, : ) = 0; end • Is this code legal/valid? • What does it do? 3
for loops 4
for loops im = imread(‘blacklab. jpg’); for row = 1: 2: size(im, 1) im(row, : ) = 0; end im = imread(‘blacklab. jpg’); for row = [1 3 5 7 9…keep going… 357] im(row, : ) = 0; end 5
for loops vs. while loops % for loop for row = 1: 2: end im(row, : ) = 255; end % while loop row = 1; while row <= end im(row, : ) = 255; row = row + 2; end % vector (non-loop) % not always possible to vectorize your loop, % but *very* preferable you can! im(1: 2: end, : ) = 255; 6
- Slides: 6