简体   繁体   中英

Iterating through matrix rows in Octave without using an index or for loop

I am trying to understand if it's possible to use Octave more efficiently by removing the for loop I'm using to calculate a formula on each row of a matrix X:

myscalar = 0
for i = 1:size(X, 1),
  myscalar += X(i, :) * y(i) % y is a vector of dimension size(X, 1)
  ...

The formula is more complicate than adding to a scalar. The question here is really how to iterate through X rows without an index, so that I can eliminate the for loop.

Yes, you can use broadcasting for this (you will need 3.6.0 or later). If you know python, this is the same ( an explanation from python ). Simply multiply the matrix by the column. Finnaly, cumsum does the addition but we only want the last row.

newx      = X .* y;
myscalars = cumsum (newx, 1) (end,:);

or in one line without temp variables

myscalars = cumsum (X .* y, 1) (end,:);

If the sizes are right, broadcasting is automatically performed. For example:

octave> a = [ 1 2 3
              1 2 3
              1 2 3];
octave> b = [ 1 0 2];
octave> a .* b'
warning: product: automatic broadcasting operation applied
ans =

   1   0   6
   1   0   6
   1   0   6

octave> a .* b
warning: product: automatic broadcasting operation applied
ans =

   1   2   3
   0   0   0
   2   4   6

The reason for the warning is that it's a new feature that may confuse users and is not existent in Matlab. You can turn it off permanentely by adding warning ("off", "Octave:broadcast") to your .octaverc file

For anyone using an older version of Octave, the same can be accomplished by calling bsxfun directly.

myscalars = cumsum (bsxfun (@times, X, y), 1) (end,:);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM