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

huangapple go评论76阅读模式
英文:

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;
});

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

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定