1 of 9

Slide Notes

DownloadGo Live

Loops

Published on Nov 22, 2016

No Description

PRESENTATION OUTLINE

Loops

For and While Loops

For vs While

  • Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How to choose: for loops if you know how many times you need to repeat the loops while loops if you need to keep repeating the instructions until a criterion is met

For loops

  • Structure for loops is for index = [matrix] commands to executed end
  • Example (open new script file) for k=[1,3,7] k end

Example for loops

  • A common way to use a for loop is in defining a new matrix. for k=1:5 a(k)=k^2 end
  • In command window a= 1 a= 4 a= 4 9 a= 4 9 16 a= 1 4 9 16 25

continue

  • In command window a= 1 a= 4 a= 4 9 a= 4 9 16 a= 1 4 9 16 25

While loops

  • The big difference between while and for loops is MATLAB decides how many times to repeat the loops While loops continue until the criteria are met The format is while criteria command to be executed end

Example while loops

  • h=0; while h
  • What do you think will happens if we execute this coding? How about you try it yourself and see what happens?

Continue

  • The coding continue to loops until k=2 but the answer has k=3.
  • Why is that? Because the respond is k=h+1

For more information

please download the latest file about loops in Morpheus