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 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? 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 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 B Is not really possible Correct Not a problem in this case, though when we get to while loops we will experience code that never finishes (infinite loop)

3 for loops Is this code legal/valid? What does it do?
im = imread(‘blacklab.jpg’); for row = [ ] im(row,:,:) = 0; end Is this code legal/valid? What does it do? See next slide for answer.

4 for loops

5 for loops im = imread(‘blacklab.jpg’); for row = 1:2:size(im,1)
im(row,:,:) = 0; end for row = [ …keep going…357]

6 for loops vs. while loops
for row = 1:2:end im(row,:,:) = 255; end row = 1; while row <= end im(row,:,:) = 255; row = row + 2; end A good slide for students to bookmark and refer to often. % vector (non-loop) % not always possible to vectorize your loop, % but *very* preferable you can! im(1:2:end,:,:) = 255;


Download ppt "Introduction to Programming in MATLAB"

Similar presentations


Ads by Google