Iterate over each row in matrix Octave

You can transpose the matrix first and then do a for statement like so:

for i = z'
    disp(i(1))
    disp(i(2))
end

Although in this case you won't have an index stating which row you are using


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

Tags:

Octave