SlideShare une entreprise Scribd logo
1  sur  16
MATLAB control structures continued

                       CIV1900: Engineering Skills
Recap
Control structures determine what gets executed

  • control flow is determined by control structures
  • MATLAB has four control structures

  • two for deciding between alternatives:
       • if statements
       • switch statements


  • two for repeating (a.k.a. looping or iteration):
       • while loops
       • for loops


  • MATLAB also has implicit loops over arrays



 CIV1900                     MATLAB control structures   3
An if statement runs the body when the condition is true

  • if statements are of the form:
    if <condition>
        <body>
    end

  • if and end are keywords (can't be used as variables)
  • <condition> is a logical expression which can be evaluated
    to true or false
  • <body> is the body of the if statement
       • one or more statements
       • only executed when the condition evaluates to true




 CIV1900                       MATLAB control structures         4
You can explore the conditions on their own

  • try all of these conditional operators:

  Operator   Description                    Operator       Description
  x > 4      greater than                   x < 4          less than
  x >= 4     greater than or equal to       x <= 4         less than or equal to
  x == 4     equal to                       x ~= 4         not equal to

  • for example:
  • >> x = 4
    >> x == 4
    ans = 1
  • equality is == to distinguish from assignment
  • remember ans is a logical not a number

 CIV1900                       MATLAB control structures                           5
What about if the condition is false?

  • an else clause can be run if the condition is false:
    if <condition>
      <true-body>
    else
      <false-body>
    end

  • else is also a keyword
  • <false-body> is run when the condition is false




 CIV1900                   MATLAB control structures       6
Else body only runs if none of the conditions are true

  • the general scheme looks like this:
    if <condition1>
       <true-body1>
    elseif <condition2>
       <true-body2>
    …
    else
       <false-body>
    end

  • where the elseif and else clauses are optional
  • and the elseif clause can be repeated for more conditions

 CIV1900                  MATLAB control structures             7
while statements are like repeating if statements

  • a while loop repeats the body while the condition stays true
  • the general scheme looks very similar to an if statement:
    while <condition>
       <body>
    end

  • while and end are keywords

  • when <condition> is false the loop will not execute again




 CIV1900                 MATLAB control structures                 8
The condition is evaluated before the body is executed

  • a while loop repeats the following steps
       • first, evaluating the conditional expression
       • if the condition is true, run the body
       • if the condition is false, jump to the statement after the body


  • an iteration is a single execution of the body
  • the condition is evaluated before each iteration begins

  • sometimes the body may never get executed




 CIV1900                        MATLAB control structures                  9
A very common idiom for while loops

     x = 1;
     while x <= 3
        fprintf('In the loop, x = %d n',x);
        x = x + 1;
     end
     fprintf('After the loop, x = %d n',x);

  • the output will look like this:
    In the loop, x = 1
    In the loop, x = 2
    In the loop, x = 3
    After the loop, x = 4

 CIV1900                   MATLAB control structures   10
Not updating the loop variable is a common mistake

  • what happens when we run this program?
    x = 1;
    while x <= 3
        fprintf('In the loop, x = %d n',x);
    end
    fprintf('After the loop, x = %d n',x);



  •   you can stop the infinite loop by pressing Control-C
  •   x is never updated in the body, so it stays at 1
  •   the condition is never false
  •   the loop never stops!

 CIV1900                   MATLAB control structures         11
Looping over array indices is common

     values = [1 5 2 8 -3 4];
     i = 1;
     total = 0;
     while i <= length(values)
        total = total + values(i);
        i = i + 1;
     end
     fprintf('The total is %d n',total);

  • the length function returns the length of a vector
  • the loop variable i ranges from 1 up to 6
  • single letter loop variables, especially i, j, and k are common

 CIV1900                  MATLAB control structures                   12
for loops simplify looping over arrays

  • for loops iterate over each element of an array or range

  • they have the general form
    for <variable> = <array>
         <body>
    end

  • <body> is run once for each element of the array

     for x = 1:3
        fprintf(‘x is now %d n’,x);
     end


 CIV1900                 MATLAB control structures             13
for loops really simplify our previous example

     marks = [75, 80, 71, 82, 86];

     total = 0;
     for m = marks
         total = total + m;
     end

     avg = total/length(marks);
     fprintf('Average mark %d n', avg);

  • variable m is assigned the value 75, then 80, then 71, …
  • after each time m is assigned, the for loop body is run

 CIV1900                  MATLAB control structures            14
for loops can be used with ranges

     for i = 1:2:8
         fprintf('i = %d n', i);
     end
     fprintf('after the loop i = %d n', i);

  • i will be assigned 1, then 3, then 5, …
  • so the output is
    i = 1                              Note:
    i = 3                              That the increment can
                                       also be negative e.g.
    i = 5
    i = 7                                      8:-2:1
    after the loop i = 7

 CIV1900                  MATLAB control structures             15
When we need the index, loop over 1:length(A)

 • for example, to find the index of the maximum in values:
   maxval = values(1);
   maxindex = 1;
   for i = 1:length(values)
         if values(i) > maxval
             maxval = values(i);
             maxindex = i;
         end
   end
   fprintf('max at index %d n', maxindex]);




 CIV1900                MATLAB control structures             16

Contenu connexe

Tendances

Tendances (20)

MATLAB Basics-Part1
MATLAB Basics-Part1MATLAB Basics-Part1
MATLAB Basics-Part1
 
Matlab m files and scripts
Matlab m files and scriptsMatlab m files and scripts
Matlab m files and scripts
 
bisection method
bisection methodbisection method
bisection method
 
MATLAB - Arrays and Matrices
MATLAB - Arrays and MatricesMATLAB - Arrays and Matrices
MATLAB - Arrays and Matrices
 
MATLAB INTRODUCTION
MATLAB INTRODUCTIONMATLAB INTRODUCTION
MATLAB INTRODUCTION
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
Matlab ch1 (4)
Matlab ch1 (4)Matlab ch1 (4)
Matlab ch1 (4)
 
MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlab
 
Matlab plotting
Matlab plottingMatlab plotting
Matlab plotting
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
 
Matlab-Data types and operators
Matlab-Data types and operatorsMatlab-Data types and operators
Matlab-Data types and operators
 
Basic operators in matlab
Basic operators in matlabBasic operators in matlab
Basic operators in matlab
 
Error analysis
Error analysisError analysis
Error analysis
 
Boolean Logic
Boolean LogicBoolean Logic
Boolean Logic
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Importance of matlab
Importance of matlabImportance of matlab
Importance of matlab
 
Matlab Overviiew
Matlab OverviiewMatlab Overviiew
Matlab Overviiew
 

En vedette

CIV1900 Matlab - Plotting & Coursework
CIV1900 Matlab - Plotting & CourseworkCIV1900 Matlab - Plotting & Coursework
CIV1900 Matlab - Plotting & CourseworkTUOS-Sam
 
Variables in matlab
Variables in matlabVariables in matlab
Variables in matlabTUOS-Sam
 
Introduction to Matlab Scripts
Introduction to Matlab ScriptsIntroduction to Matlab Scripts
Introduction to Matlab ScriptsShameer Ahmed Koya
 
User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4Shameer Ahmed Koya
 
R Programming: Numeric Functions In R
R Programming: Numeric Functions In RR Programming: Numeric Functions In R
R Programming: Numeric Functions In RRsquared Academy
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshopVinay Kumar
 
metode numerik stepest descent dengan rerata aritmatika
metode numerik stepest descent dengan rerata aritmatikametode numerik stepest descent dengan rerata aritmatika
metode numerik stepest descent dengan rerata aritmatikaSabarinsyah Piliang
 
Modul1 metode bagi dua Praktikum Metode Numerik
Modul1 metode bagi dua Praktikum Metode NumerikModul1 metode bagi dua Praktikum Metode Numerik
Modul1 metode bagi dua Praktikum Metode NumerikJames Montolalu
 
Anonymous and Inline Functions in MATLAB
Anonymous and Inline Functions in MATLABAnonymous and Inline Functions in MATLAB
Anonymous and Inline Functions in MATLABShameer Ahmed Koya
 
Modul2 metode regula falsi praktikum metode numerik
Modul2 metode regula falsi praktikum metode numerikModul2 metode regula falsi praktikum metode numerik
Modul2 metode regula falsi praktikum metode numerikJames Montolalu
 
User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2Shameer Ahmed Koya
 
Jumping statements
Jumping statementsJumping statements
Jumping statementsSuneel Dogra
 
Metode numerik-buku-ajar-unila
Metode numerik-buku-ajar-unilaMetode numerik-buku-ajar-unila
Metode numerik-buku-ajar-unilaIbad Ahmad
 
Band Combination of Landsat 8 Earth-observing Satellite Images
Band Combination of Landsat 8 Earth-observing Satellite ImagesBand Combination of Landsat 8 Earth-observing Satellite Images
Band Combination of Landsat 8 Earth-observing Satellite ImagesKabir Uddin
 
mat lab introduction and basics to learn
mat lab introduction and basics to learnmat lab introduction and basics to learn
mat lab introduction and basics to learnpavan373
 
Panduan matlab
Panduan matlabPanduan matlab
Panduan matlabgiya12001
 

En vedette (20)

CIV1900 Matlab - Plotting & Coursework
CIV1900 Matlab - Plotting & CourseworkCIV1900 Matlab - Plotting & Coursework
CIV1900 Matlab - Plotting & Coursework
 
Variables in matlab
Variables in matlabVariables in matlab
Variables in matlab
 
Matlab time series example
Matlab time series exampleMatlab time series example
Matlab time series example
 
Introduction to Matlab Scripts
Introduction to Matlab ScriptsIntroduction to Matlab Scripts
Introduction to Matlab Scripts
 
User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4
 
R Programming: Numeric Functions In R
R Programming: Numeric Functions In RR Programming: Numeric Functions In R
R Programming: Numeric Functions In R
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
 
metode numerik stepest descent dengan rerata aritmatika
metode numerik stepest descent dengan rerata aritmatikametode numerik stepest descent dengan rerata aritmatika
metode numerik stepest descent dengan rerata aritmatika
 
Modul1 metode bagi dua Praktikum Metode Numerik
Modul1 metode bagi dua Praktikum Metode NumerikModul1 metode bagi dua Praktikum Metode Numerik
Modul1 metode bagi dua Praktikum Metode Numerik
 
Anonymous and Inline Functions in MATLAB
Anonymous and Inline Functions in MATLABAnonymous and Inline Functions in MATLAB
Anonymous and Inline Functions in MATLAB
 
Modul2 metode regula falsi praktikum metode numerik
Modul2 metode regula falsi praktikum metode numerikModul2 metode regula falsi praktikum metode numerik
Modul2 metode regula falsi praktikum metode numerik
 
Fungsi grafik di matlab
Fungsi grafik di matlabFungsi grafik di matlab
Fungsi grafik di matlab
 
User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2
 
Jumping statements
Jumping statementsJumping statements
Jumping statements
 
Metode numerik-buku-ajar-unila
Metode numerik-buku-ajar-unilaMetode numerik-buku-ajar-unila
Metode numerik-buku-ajar-unila
 
MATLAB Scripts - Examples
MATLAB Scripts - ExamplesMATLAB Scripts - Examples
MATLAB Scripts - Examples
 
Band Combination of Landsat 8 Earth-observing Satellite Images
Band Combination of Landsat 8 Earth-observing Satellite ImagesBand Combination of Landsat 8 Earth-observing Satellite Images
Band Combination of Landsat 8 Earth-observing Satellite Images
 
Matlab 1 level_1
Matlab 1 level_1Matlab 1 level_1
Matlab 1 level_1
 
mat lab introduction and basics to learn
mat lab introduction and basics to learnmat lab introduction and basics to learn
mat lab introduction and basics to learn
 
Panduan matlab
Panduan matlabPanduan matlab
Panduan matlab
 

Similaire à Loops in matlab

Mesics lecture 7 iteration and repetitive executions
Mesics lecture 7   iteration and repetitive executionsMesics lecture 7   iteration and repetitive executions
Mesics lecture 7 iteration and repetitive executionseShikshak
 
Repetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesRepetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesJason J Pulikkottil
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
 
Unit II chapter 4 Loops in C
Unit II chapter 4 Loops in CUnit II chapter 4 Loops in C
Unit II chapter 4 Loops in CSowmya Jyothi
 
Control statements anil
Control statements anilControl statements anil
Control statements anilAnil Dutt
 
Chapter 13.1.5
Chapter 13.1.5Chapter 13.1.5
Chapter 13.1.5patcha535
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
Loop(for, while, do while) condition Presentation
Loop(for, while, do while) condition PresentationLoop(for, while, do while) condition Presentation
Loop(for, while, do while) condition PresentationBadrul Alam
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in JavaJin Castor
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While LoopAbhishek Choksi
 

Similaire à Loops in matlab (20)

Mesics lecture 7 iteration and repetitive executions
Mesics lecture 7   iteration and repetitive executionsMesics lecture 7   iteration and repetitive executions
Mesics lecture 7 iteration and repetitive executions
 
matrices_and_loops.pptx
matrices_and_loops.pptxmatrices_and_loops.pptx
matrices_and_loops.pptx
 
Programming loop
Programming loopProgramming loop
Programming loop
 
C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
 
Iteration
IterationIteration
Iteration
 
Repetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesRepetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniques
 
Looping statements
Looping statementsLooping statements
Looping statements
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
Unit II chapter 4 Loops in C
Unit II chapter 4 Loops in CUnit II chapter 4 Loops in C
Unit II chapter 4 Loops in C
 
M C6java6
M C6java6M C6java6
M C6java6
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
Chapter 13.1.5
Chapter 13.1.5Chapter 13.1.5
Chapter 13.1.5
 
control structure
control structurecontrol structure
control structure
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Loop(for, while, do while) condition Presentation
Loop(for, while, do while) condition PresentationLoop(for, while, do while) condition Presentation
Loop(for, while, do while) condition Presentation
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
cpu.pdf
cpu.pdfcpu.pdf
cpu.pdf
 
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 

Loops in matlab

  • 1. MATLAB control structures continued CIV1900: Engineering Skills
  • 3. Control structures determine what gets executed • control flow is determined by control structures • MATLAB has four control structures • two for deciding between alternatives: • if statements • switch statements • two for repeating (a.k.a. looping or iteration): • while loops • for loops • MATLAB also has implicit loops over arrays CIV1900 MATLAB control structures 3
  • 4. An if statement runs the body when the condition is true • if statements are of the form: if <condition> <body> end • if and end are keywords (can't be used as variables) • <condition> is a logical expression which can be evaluated to true or false • <body> is the body of the if statement • one or more statements • only executed when the condition evaluates to true CIV1900 MATLAB control structures 4
  • 5. You can explore the conditions on their own • try all of these conditional operators: Operator Description Operator Description x > 4 greater than x < 4 less than x >= 4 greater than or equal to x <= 4 less than or equal to x == 4 equal to x ~= 4 not equal to • for example: • >> x = 4 >> x == 4 ans = 1 • equality is == to distinguish from assignment • remember ans is a logical not a number CIV1900 MATLAB control structures 5
  • 6. What about if the condition is false? • an else clause can be run if the condition is false: if <condition> <true-body> else <false-body> end • else is also a keyword • <false-body> is run when the condition is false CIV1900 MATLAB control structures 6
  • 7. Else body only runs if none of the conditions are true • the general scheme looks like this: if <condition1> <true-body1> elseif <condition2> <true-body2> … else <false-body> end • where the elseif and else clauses are optional • and the elseif clause can be repeated for more conditions CIV1900 MATLAB control structures 7
  • 8. while statements are like repeating if statements • a while loop repeats the body while the condition stays true • the general scheme looks very similar to an if statement: while <condition> <body> end • while and end are keywords • when <condition> is false the loop will not execute again CIV1900 MATLAB control structures 8
  • 9. The condition is evaluated before the body is executed • a while loop repeats the following steps • first, evaluating the conditional expression • if the condition is true, run the body • if the condition is false, jump to the statement after the body • an iteration is a single execution of the body • the condition is evaluated before each iteration begins • sometimes the body may never get executed CIV1900 MATLAB control structures 9
  • 10. A very common idiom for while loops x = 1; while x <= 3 fprintf('In the loop, x = %d n',x); x = x + 1; end fprintf('After the loop, x = %d n',x); • the output will look like this: In the loop, x = 1 In the loop, x = 2 In the loop, x = 3 After the loop, x = 4 CIV1900 MATLAB control structures 10
  • 11. Not updating the loop variable is a common mistake • what happens when we run this program? x = 1; while x <= 3 fprintf('In the loop, x = %d n',x); end fprintf('After the loop, x = %d n',x); • you can stop the infinite loop by pressing Control-C • x is never updated in the body, so it stays at 1 • the condition is never false • the loop never stops! CIV1900 MATLAB control structures 11
  • 12. Looping over array indices is common values = [1 5 2 8 -3 4]; i = 1; total = 0; while i <= length(values) total = total + values(i); i = i + 1; end fprintf('The total is %d n',total); • the length function returns the length of a vector • the loop variable i ranges from 1 up to 6 • single letter loop variables, especially i, j, and k are common CIV1900 MATLAB control structures 12
  • 13. for loops simplify looping over arrays • for loops iterate over each element of an array or range • they have the general form for <variable> = <array> <body> end • <body> is run once for each element of the array for x = 1:3 fprintf(‘x is now %d n’,x); end CIV1900 MATLAB control structures 13
  • 14. for loops really simplify our previous example marks = [75, 80, 71, 82, 86]; total = 0; for m = marks total = total + m; end avg = total/length(marks); fprintf('Average mark %d n', avg); • variable m is assigned the value 75, then 80, then 71, … • after each time m is assigned, the for loop body is run CIV1900 MATLAB control structures 14
  • 15. for loops can be used with ranges for i = 1:2:8 fprintf('i = %d n', i); end fprintf('after the loop i = %d n', i); • i will be assigned 1, then 3, then 5, … • so the output is i = 1 Note: i = 3 That the increment can also be negative e.g. i = 5 i = 7 8:-2:1 after the loop i = 7 CIV1900 MATLAB control structures 15
  • 16. When we need the index, loop over 1:length(A) • for example, to find the index of the maximum in values: maxval = values(1); maxindex = 1; for i = 1:length(values) if values(i) > maxval maxval = values(i); maxindex = i; end end fprintf('max at index %d n', maxindex]); CIV1900 MATLAB control structures 16

Notes de l'éditeur

  1. could be implemented with two opposite if statements but this would be error prone and repetitive