Loops

Review questions

  • If A is an array, what is A(2:5,3)?
  • If A is an array, what is A(2,1:4)?

Control statements

Control statements controls the flow of execution of your code. There are different types of control statements:

  • Loops.
  • Conditionals.
  • Exception handling.
  • Break statements.
  • Parallel execution.

Loops

A loop control statement allows a block of code to be executed repeatedly. There are two basic forms

  • "for" loop
  • "while" loop

An example


        A = ones(1,5)
        for i = 1:4
            A(i) = 2*i;
        end
    
  • A "for" loop starts with a "for" statement
  • An assignment state after "for" specifies the range that will be iterated as well as variable to be used.
  • It ends with the keyword "end"
  • Many statements can be included in the block between "for" and "end"

Nested for loop

A loop can contain another loop.


        A = ones(8,8)
        for i = 1:5
            for j = 2:7
                A(i,j) = i+j;
            end
        end
    
  • Each loop requires its own "end" keyword.
  • Indentation usually improves readability.

Breaking statements

Execution of statements inside a loop can be interrupted or diverted.

  • the "break" statement exit a loop
  • the "continue" statement skips to the next iteration of the loop

Worksheet tasks

For today's exercise, complete the following tasks using "for" loops

  • Create the array [1 2 3 ... 10]
  • Create the two dimensional array whose i-j entry is i+j
  • Create the gradient effect on this image

Can you recreat this?