er quick matrix.assign(0); for (int row=0; row < rows; row++) { for (int column=0; column < columns; column++) { if (someCondition) matrix.setQuick(row,column,someValue); } } // poor matrix.assign(0); for (int row=rows; --row>= 0; ) { for (int column=columns; --column >= 0; ) { if (someCondition) matrix.setQuick(row,column,someValue); } } If for whatever reasons you can't iterate properly, consider to create an empty dense matrix, store your non-zeros in it, then call
sparse.assign(dense). Under the circumstances, this is still rather quick.
Fast iteration over non-zeros can be done via {@link #forEachNonZero}, which supplies your function with row, column and value of each nonzero. Although the internally implemented version is a bit more sophisticated, here is how a quite efficient user-level matrix-vector multiplication could look like:
// Linear algebraic y = A * x A.forEachNonZero( new cern.colt.function.IntIntDoubleFunction() { public double apply(int row, int column, double value) { y.setQuick(row,y.getQuick(row) + value * x.getQuick(column)); return value; } } ); |
Here is how a a quite efficient user-level combined scaling operation could look like:
// Elementwise A = A + alpha*B B.forEachNonZero( new cern.colt.function.IntIntDoubleFunction() { public double apply(int row, int column, double value) { A.setQuick(row,column,A.getQuick(row,column) + alpha*value); return value; } } ); |
Method {@link #assign(DoubleMatrix2D,cern.colt.function.DoubleDoubleFunction)} does just that if you supply {@link cern.jet.math.Functions#plusMult} as argument.
@author wolfgang.hoschek@cern.ch
@version 0.9, 04/14/2000