Frage

In Parallel Colt, how do I add a vector to every row of a matrix, preferably in-place? In particular, I have a DoubleMatrix1D I'd like to add to each row of a DoubleMatrix2D. It seems like this should be straightforward, but it's not clear from the Javadoc. (I can of course do it by hand, but it seems odd no such capability would be built in).

War es hilfreich?

Lösung

So, to add a m-dimensional vector (say, aVector) to the i'th row of a nxm matrix (say, aMatrix), you will need to do the following:

// new matrix where each row is the vector you want to add, i.e., aVector
DoubleMatrix2D otherMatrix = DoubleFactory2D.sparse.make(aVector.toArray(), n);
DoubleDoubleFunction plus = new DoubleDoubleFunction() {
    public double apply(double a, double b) { return a+b; }
};
aMatrix.assign(otherMatrix, plus);    

The API says this about the assign method:

assign(DoubleMatrix2D y, DoubleDoubleFunction function) 
    Assigns the result of a function to each cell; x[row,col] = function(x[row,col],y[row,col]).

I have not tested the DoubleFactory2D#make() method myself. If it creates a matrix where your aVector is incorporated as columns instead of rows in otherMatrix, then use DoubleAlgebra#transpose() to get the transpose before using the assign() step.

EDIT

There is a much simpler way of adding a row in-place, in case you want change only a particular (say, the i-th) row:

aMatrix.viewRow(i).assign(aVector); 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top