Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over each row in matrix Octave

Tags:

octave

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
like image 267
Dan Kanze Avatar asked Sep 28 '14 17:09

Dan Kanze


People also ask

How do you make a loop in Octave?

In general, the syntax of a for loop is for variable = vector statements end where variable is the loop index, vector is a vector of some desired length containing the numbers to step through, and statements are the commands you'd like Octave to execute at each iteration.

What is the syntax of range in Octave?

defines the set of values ' [ 1, 4 ] '. Although a range constant specifies a row vector, Octave does not convert range constants to vectors unless it is necessary to do so. This allows you to write a constant like ' 1 : 10000 ' without using 80,000 bytes of storage on a typical 32-bit workstation. y = [ 0 : 0.1 : 1];

How do you end a loop in Octave?

break statement It is used to exit from a loop.


1 Answers

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
like image 108
Andy Avatar answered Sep 21 '22 13:09

Andy