# 如何创建一个具有全为1的列的2D双数组

go评论65阅读模式

How to create a 2D double array with column of ones

# 问题

``````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}}
``````

``````MatrixUtils.createRealMatrix(new double[][]{{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}})
``````

``````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)
&gt;&gt; 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

``````double[][] m = new double[rows][cols];
for (int i = 0; i &lt; rows; i++)
Arrays.fill(m[i], 1.0);
``````

You can use `Arrays.fill`:

``````double[][] m = new double[rows][cols];
for (int i = 0; i &lt; rows; i++)
Arrays.fill(m[i], 1.0);
``````

# 答案2

``````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 -&gt; {
double[] row = new double[cols];
Arrays.fill(row, 1.0);
return row;
});
``````

• 本文由 发表于 2020年7月21日 22:38:07
• 转载请务必保留本文链接：https://go.coder-hub.com/63016962.html
• java
• matrix
• matrix-multiplication
• vector

go 62

go 47

go 108

go 83