如何在ojAlgo矩阵中按行或列计算元素平均值并得到结果向量?
Absolutely! ojAlgo fully supports computing row-wise and column-wise averages of a matrix to produce the corresponding mean vectors—just like you're used to with NumPy and MATLAB. Let me walk you through exactly how to implement this with your example matrix.
Step 1: Create Your Example Matrix
First, we'll initialize the 2×3 matrix you mentioned using ojAlgo's PrimitiveMatrix (the go-to type for double-precision matrices):
import org.ojalgo.matrix.PrimitiveMatrix; // Define your matrix A = [[1, 2, 3],[4, 5, 6]] PrimitiveMatrix matrixA = PrimitiveMatrix.FACTORY.rows(new double[][]{{1, 2, 3}, {4, 5, 6}});
Step 2: Calculate Column-Wise Averages
To get the 3-element vector of column means (your expected [2.5, 3.5, 4.5]), use the calculateColumnMeans() method:
PrimitiveMatrix.VectorView columnMeans = matrixA.calculateColumnMeans(); // Result: [2.5, 3.5, 4.5]
Step 3: Calculate Row-Wise Averages
For the 2-element vector of row means (your expected [2, 5]), use the calculateRowMeans() method:
PrimitiveMatrix.VectorView rowMeans = matrixA.calculateRowMeans(); // Result: [2.0, 5.0]
Convert Vectors to Raw Double Arrays (Optional)
If you need to work with standard Java double[] instead of ojAlgo's vector type, use the toRawCopy1D() method:
double[] columnMeansArray = columnMeans.toRawCopy1D(); double[] rowMeansArray = rowMeans.toRawCopy1D();
ojAlgo's matrix API is designed to handle these common statistical operations smoothly, so you won't need to roll your own loops for basic mean calculations.
内容的提问来源于stack exchange,提问作者영민 카이 앤절

