Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple matrix operations (2D & 3D) using Colt library

I want to perform simple matrix operations in my code and I use the Colt library

(see in here: http://acs.lbl.gov/software/colt/api/index.html)

I want for example to add/subtract/multiply matrices, add/subtract/multiply/divide a scalar to each cell of a matrix etc...But there seem to be no such functions in this library.

However, I found this comment: https://stackoverflow.com/a/10815643/2866701

How can I use the assign() command to perform these simple operations in my code?

like image 956
Konstantinos_S Avatar asked Jan 26 '26 16:01

Konstantinos_S


1 Answers

Colt provides a more general framework under the assign() methods. For example, if you want to add a scalar to each cell of a matrix, you could do the following:

double scalar_to_add  = 0.5;
DoubleMatrix2D matrix = new DenseDoubleMatrix2D(10, 10); // creates an empty 10x10 matrix
matrix.assign(DoubleFunctions.plus(scalar_to_add)); // adds the scalar to each cell

Standard functions are available as static methods in the DoubleFunctions class. Others need to be written by you.

If you want vector addition instead of just adding a scalar value, the second argument of assign() needs to be a DoubleDoubleFunction. For example,

DoubleDoubleFunction plus = new DoubleDoubleFunction() {
    public double apply(double a, double b) { return a+b; }
};    
DoubleMatrix1D aVector = ... // some vector
DoubleMatrix1D anotherVector = ... // another vector of same size
aVector.assign(anotherVector, plus); // now you have the vector sum
like image 82
Chthonic Project Avatar answered Jan 28 '26 05:01

Chthonic Project



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!