关于 Commons-math 中的矩阵算法小结

来源:互联网 发布:小米盒子免费视频软件 编辑:程序博客网 时间:2024/06/05 05:27

对于大的数据量,转换成矩阵或者行列式进行计算会将运算效率提高。

所用jar包:Commons-math3-3.5.jar

相关API:http://commons.apache.org/proper/commons-math/javadocs/api-3.3/

1.double[]数组转换为矩阵

double[] martxData = {1d,2d,3d};RealMatrix matrix = new Array2DRowRealMatrix(martxData);
2.矩阵求逆

public static RealMatrix inverseMatrix(RealMatrix matrix) {     LUDecomposition LUDe = new LUDecomposition(matrix);     DecompositionSolver solver = LUDe.getSolver();     RealMatrix result = solver.getInverse();     return result;}
3.按列合并矩阵[a/b]

public static RealMatrix combinedCol(RealMatrix a, RealMatrix b) {     int col = a.getColumnDimension() + b.getColumnDimension();     int row = a.getRowDimension();     RealMatrix result = MatrixUtils.createRealMatrix(row, col);     int temp = a.getColumnDimension();     for (int i = 0; i < col; i++) {         if (i < a.getColumnDimension()) {             for (int j = 0; j < row; j++) {                 result.setEntry(j, i, a.getEntry(j, i));             }         } else {             for (int j = 0; j < row; j++) {                 result.setEntry(j, i, b.getEntry(j, i - temp));             }         }     }     return result;}
4.按行合并矩阵[a,b]

public static RealMatrix combinedRow(RealMatrix a, RealMatrix b) {     int col = a.getColumnDimension();     int row = a.getRowDimension() + b.getRowDimension();     int temp = a.getRowDimension();     RealMatrix result = MatrixUtils.createRealMatrix(row, col);     for (int i = 0; i < row; i++) {         if (i < a.getRowDimension()) {             for (int j = 0; j < col; j++) {                 result.setEntry(i, j, a.getEntry(i, j));             }         } else {             for (int j = 0; j < col; j++) {                 result.setEntry(i, j, b.getEntry(i - temp, j));             }         }     }     return result;}
5.返回各列平均值1*col

public static RealMatrix mean(RealMatrix a) {     int col = a.getColumnDimension();     double[] data = new double[col];     for (int i = 0; i < col; i++) {         data[i] = new Mean().evaluate(a.getColumn(i));     }     RealMatrix result = MatrixUtils.createRowRealMatrix(data);     return result;}
6.返回各行平均值row*1
public static RealMatrix meanRow(RealMatrix a) {     int row = a.getRowDimension();     double[] data = new double[row];     for (int i = 0; i < row; i++) {         data[i] = new Mean().evaluate(a.getRow(i));     }     RealMatrix result = MatrixUtils.createRowRealMatrix(data);     return result;}
7.获取指定列的元素

public static RealMatrix getColMatrix(RealMatrix absMatrix) {     RealMatrix a = absMatrix.getColumnMatrix(1);//此处的1指第二列     return a;}
8.矩阵相乘、获取返回的第一列数据

RealMatrix pMatrix = matrix.multiply(matrix2);//matrix和matrix2相乘double[] y = sMatrix.scalarMultiply(1/1).getColumn(0);//获取到第一列for (int i = 0; i < y.length; i++) {System.out.println(y[i]);;}












0 0
原创粉丝点击