1 / 7

Introduction to Programming in MATLAB

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!. Loops!.

nell
Download Presentation

Introduction to Programming in MATLAB

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 www.peerinstruction4cs.org.

  2. LOOPS!

  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!

  4. 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

  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: • 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

  6. 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

  7. 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

More Related