英文:
How to create a 2D double array with column of ones
问题
我需要使用Apache的RealMatrix在Java中计算列的总和。 这将像这样工作:
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.MatrixUtils;
double[][] values = {{1.0, 2.0}, {3.0, 4.0}, {5.0, 6.0}};
RealMatrix matrix = MatrixUtils.createRealMatrix(values);
MatrixUtils.createRealMatrix(new double[][]{{1, 1, 1}}).multiply(matrix)
>> Array2DRowRealMatrix{{9.0, 12.0}}
但是,当我声明ones时,我想要使它更加通用,例如:
MatrixUtils.createRealMatrix(new double[][]{{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}})
我想知道是否有一种方式可以在大括号内预先声明我想要的ones的数量?
假设我想要numberOfOnes = 10
,那么:
MatrixUtils.createRealMatrix(new double[][]{{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}})
我正在努力寻找一种使这个过程更加通用的方法。 有什么帮助吗?
英文:
I am in need of computing column sums in java using apache's RealMatrix. This would work like this:
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.MatrixUtils;
double[][] values = {{1.0, 2.0}, {3.0, 4.0}, {5.0, 6.0}};
RealMatrix matrix = MatrixUtils.createRealMatrix(values);
MatrixUtils.createRealMatrix(new double[][]{{1, 1, 1}}).multiply(matrix)
>> Array2DRowRealMatrix{{9.0,12.0}}
However, I would like to make it general when it comes to declaring ones in
MatrixUtils.createRealMatrix(new double[][]{{1, 1, 1}})
Is there a way to pre-declare the number of ones I want inside a curly bracket?
Say I want numberOfOnes = 10
, then:
MatrixUtils.createRealMatrix(new double[][]{{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}})
I am struggling to find a way to make this general. Any help?
答案1
得分: 1
你可以使用 Arrays.fill
:
double[][] m = new double[rows][cols];
for (int i = 0; i < rows; i++)
Arrays.fill(m[i], 1.0);
英文:
You can use Arrays.fill
:
double[][] m = new double[rows][cols];
for (int i = 0; i < rows; i++)
Arrays.fill(m[i], 1.0);
答案2
得分: 0
你可以使用 Arrays.setAll
方法来分别处理每一行:
double[][] m = new double[rows][];
Arrays.setAll(m, i -> {
double[] row = new double[cols];
Arrays.fill(row, 1.0);
return row;
});
英文:
You can use Arrays.setAll
method to process each row separately:
double[][] m = new double[rows][];
Arrays.setAll(m, i -> {
double[] row = new double[cols];
Arrays.fill(row, 1.0);
return row;
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论