Download presentation
Presentation is loading. Please wait.
Published bySibyl Moore Modified over 8 years ago
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 www.peerinstruction4cs.org.Dr. Cynthia Lee, UCSDCreative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported Licensewww.peerinstruction4cs.org 1
2
LOOPS! 2
3
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
4
for loop Copy-and-paste version » myvector(1) = 0 » myvector(2) = 0 » myvector(3) = 0 » myvector(4) = 0 » myvector(5) = 0 » myvector(6) = 0 for loop version » for i = 1:6 myvector(i) = 0 end Of course, you can also do this: » myvector(1:6) = zeros(1,6) 4
5
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.Less prone to errors in the code II.Easier to read the code III.Code runs faster IV.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
6
for loop Copy-and-paste version » myvector(1) = 0 » myvector(2) = 0 » myvector(3) = 0 » myvecter(4) = 0 » myvector(5) = 0 » myvector(6) = 0 for loop version » for i = 1:6 myvector(i) = 0 end Of course, you can also do this: » myvector(1:6) = zeros(1,6) 6
7
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.