我想在代码中执行简单的矩阵操作,并使用Colt库。
(见此处:http://acs.lbl.gov/software/colt/api/index.html)
例如,我想要加/减/乘矩阵,加/减/乘/除一个标量到矩阵etc...But的每个单元格中,这个库中似乎没有这样的函数。
然而,我发现了这样的评论:https://stackoverflow.com/a/10815643/2866701
如何在代码中使用assign()命令来执行这些简单的操作?
发布于 2014-01-22 11:03:37
Colt在assign()方法下提供了一个更通用的框架。例如,如果要向矩阵的每个单元格添加标量,可以执行以下操作:
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标准函数在DoubleFunctions类中可作为静态方法使用。其他的需要由你来写。
如果您想要向量加法而不只是添加标量值,那么assign()的第二个参数需要是一个DoubleDoubleFunction。例如,
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发布于 2013-10-18 12:34:31
为什么不试试la4j (线性代数用于Java)呢?它很容易使用:
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还有transform()方法,类似于Colt的assign()。它可用于以下方面:
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);
}
});但它只适用于二维矩阵。
https://stackoverflow.com/questions/19424276
复制相似问题