70 likes | 208 Vues
This presentation by Dr. Cynthia Lee from UCSD explores the use of loops in MATLAB programming. It emphasizes the importance of avoiding repetitive code through loops, scripts, and functions, which not only reduces typing but also minimizes errors and enhances code readability. The lecture discusses the practical applications of loops, such as initializing vectors and performing calculations like sums and averages. Loops allow programmers to run processes repeatedly, making code execution more efficient and flexible.
E N D
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.
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!
for loop Copy-and-paste version for loop version for i = 1:6 myvector(i) = 0 end Of course, you can also do this: myvector(1:6) = zeros(1,6) • myvector(1) = 0 • myvector(2) = 0 • myvector(3) = 0 • myvector(4) = 0 • myvector(5) = 0 • myvector(6) = 0
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: • 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? • 1 of them (b) 2 of them (c) 3 of them (d) 4 of them
for loop Copy-and-paste version for loop version for i = 1:6 myvector(i) = 0 end Of course, you can also do this: myvector(1:6) = zeros(1,6) • myvector(1) = 0 • myvector(2) = 0 • myvector(3) = 0 • myvecter(4) = 0 • myvector(5) = 0 • myvector(6) = 0
What does this code do? • mystery = 1 • for i = 1:10 mystery = mystery * i end • Computes the sum of the integers from 1 to 8 • Computses the average of the integers from 1 to 10 • Computes the factorial of 10 • Computes the median of the integers from 1 to 10