Reputation: 65
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?
Upvotes: 3
Views: 4280
Reputation: 8346
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
Upvotes: 4
Reputation: 2552
Why don't you try la4j (Linear Algebra for Java)? It is easy to use:
Matrix a = new Basci2DMatrix(new double[][]{
{ 1.0, 2.0 },
{ 3.0, 4.0 }
});
Matrix b = new Basci2DMatrix(new double[][]{
{ 5.0, 6.0 },
{ 7.0, 8.0 }
});
Matrix c = a.multiply(b); // a * b
Matrix d = a.add(b); // a + b
Matrix e = a.subtract(b); // a - b
There is also transform()
method that is similar to Colt's assign()
. It can be used as following:
Matrix f = a.transform(Matrices.INC_MATRIX); // inreases each cell by 1
Matrix g = a.transform(Matrices.asDivFunction(2)); // divides each cell by 2
// you can define your own function
Matrix h = a.transform(new MatrixFunction {
public double evaluate(int i, int j, int value) {
return value * Math.sqrt(i + j);
}
});
But it only works for 2D matrices.
Upvotes: 0