Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over 



[
1
,
…
,
20
]


{\displaystyle [1,\ldots ,20]}

.

The loops iterate rows and columns of the array printing the elements until the value 



20


{\displaystyle 20}

 is met.

Specifically, this task also shows how to break out of nested loops.



Related tasks

   Loop over multiple arrays simultaneously
   Loops/Break
   Loops/Continue
   Loops/Do-while
   Loops/Downward for
   Loops/For
   Loops/For with a specified step
   Loops/Foreach
   Loops/Increment loop index within loop body
   Loops/Infinite
   Loops/N plus one half
   Loops/Nested
   Loops/While
   Loops/with multiple ranges
   Loops/Wrong ranges


function search_almost_twenty()
% create a 100x100 matrix...
m = unifrnd(0,20, 100,100);
for i = 1:100
  for j = 1:100
    disp( m(i,j) )
    if ( abs(m(i,j) - 20) < 1e-2 )
      return
    endif
  endfor
endfor
endfunction
 
search_almost_twenty()
 
% avoiding function, we need a control variable.
m = unifrnd(0,20, 100,100);
innerloopbreak = false;
for i = 1:100
  for j = 1:100
    disp( m(i,j) )
    if ( abs(m(i,j) - 20) < 1e-2 )
      innerloopbreak = true;
      break;
    endif
  endfor
  if ( innerloopbreak )
    break;
  endif
endfor