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
LOOPS! 2
Loops! • Computer programmers are extremely lazy, in that we don’t want to do any more typing than necessary – You’ve already seen that instead of re-typing commands, we can use a script or a function • Not only do we not like re-typing—even copying and pasting lines of code is too much work for us! – Instead of copying and pasting lines of code we want to repeat some number of times, we can use a loop! 3
for loop Copy-and-paste version for loop version » myvector(1) = 0 » myvector(2) = 0 » myvector(3) = 0 » myvector(4) = 0 » for i = 1: 6 myvector(i) = 0 end » myvector(5) = 0 » myvector(6) = 0 Of course, you can also do this: » myvector(1: 6) = zeros(1, 6) 4
Software Engineering • Can you think of other reasons (besides laziness) that we might want to use programming constructs like scripts, functions, and loops to avoid re-typing or copying and pasting code? • Here are some suggested reasons: I. III. IV. Less prone to errors in the code Easier to read the code Code runs faster Code is more flexible How many of these are true reasons? (a) 1 of them (b) 2 of them (c) 3 of them (d) 4 of them 5
for loop Copy-and-paste version for loop version » myvector(1) = 0 » myvector(2) = 0 » myvector(3) = 0 » myvecter(4) = 0 » for i = 1: 6 myvector(i) = 0 end » myvector(5) = 0 » myvector(6) = 0 Of course, you can also do this: » myvector(1: 6) = zeros(1, 6) 6
What does this code do? » » mystery = 1 for i = 1: 10 mystery = mystery * i end a) Computes the sum of the integers from 1 to 8 b) Computses the average of the integers from 1 to 10 c) Computes the factorial of 10 d) Computes the median of the integers from 1 to 10 7
- Slides: 7