Iterate over each row in matrix Octave

Dan Kanze picture Dan Kanze · Sep 28, 2014 · Viewed 26.9k times · Source

How do I iterate over each row in Z where Z is a 2 * m matrix:

6.1101,17.592
5.5277,9.1302
8.5186,13.662

How do I access each Z(i)(j) inside this loop?

For example:

for i = z
  fprintf('Iterating over row: '+ i);
  disp (i:1);
  disp (i:2);
end

Would output:

Iterating over row: 1
6.1101
17.592
Iterating over row: 2
5.5277
9.1302
Iterating over row: 3
8.5186
13.662

Answer

Andy picture Andy · Sep 28, 2014

If you use for i = z when z is a matrix, then i takes the value of the first column of z (6.1101; 5.5277; 8.5186), then the second column and so on. See octave manual: The-for-Statement

If you want to iterate over all elements you could use

z = [6.1101,17.592;5.5277,9.1302;8.5186,13.662]

for i = 1:rows(z)
  for j = 1:columns(z)
    printf("z(%d,%d) = %f\n", i, j, z(i,j));
  endfor
endfor

which outputs:

z(1,1) = 6.110100
z(1,2) = 17.592000
z(2,1) = 5.527700
z(2,2) = 9.130200
z(3,1) = 8.518600
z(3,2) = 13.662000

But keep in mind that for loops are slow in octave so it may be desirable to use a vectorized method. Many functions can use a matrix input for most common calculations.

For example if you want to calculate the overall sum:

octave> sum (z(:))
ans =  60.541

Or the difference between to adjacent rows:

octave> diff (z)
ans =

  -0.58240  -8.46180
   2.99090   4.53180