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

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

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

问题

我需要使用Apache的RealMatrix在Java中计算列的总和。 这将像这样工作:

  1. import org.apache.commons.math3.linear.RealMatrix;
  2. import org.apache.commons.math3.linear.MatrixUtils;
  3. double[][] values = {{1.0, 2.0}, {3.0, 4.0}, {5.0, 6.0}};
  4. RealMatrix matrix = MatrixUtils.createRealMatrix(values);
  5. MatrixUtils.createRealMatrix(new double[][]{{1, 1, 1}}).multiply(matrix)
  6. >> Array2DRowRealMatrix{{9.0, 12.0}}

但是,当我声明ones时,我想要使它更加通用,例如:

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

我想知道是否有一种方式可以在大括号内预先声明我想要的ones的数量?

假设我想要numberOfOnes = 10,那么:

  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:

  1. import org.apache.commons.math3.linear.RealMatrix;
  2. import org.apache.commons.math3.linear.MatrixUtils;
  3. double[][] values = {{1.0, 2.0}, {3.0, 4.0}, {5.0, 6.0}};
  4. RealMatrix matrix = MatrixUtils.createRealMatrix(values);
  5. MatrixUtils.createRealMatrix(new double[][]{{1, 1, 1}}).multiply(matrix)
  6. >> Array2DRowRealMatrix{{9.0,12.0}}

However, I would like to make it general when it comes to declaring ones in

  1. 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:

  1. 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

  1. double[][] m = new double[rows][cols];
  2. for (int i = 0; i < rows; i++)
  3. Arrays.fill(m[i], 1.0);
英文:

You can use Arrays.fill:

  1. double[][] m = new double[rows][cols];
  2. for (int i = 0; i < rows; i++)
  3. Arrays.fill(m[i], 1.0);

答案2

得分: 0

你可以使用 Arrays.setAll 方法来分别处理每一行:

  1. double[][] m = new double[rows][];
  2. Arrays.setAll(m, i -> {
  3. double[] row = new double[cols];
  4. Arrays.fill(row, 1.0);
  5. return row;
  6. });
英文:

You can use Arrays.setAll method to process each row separately:

  1. double[][] m = new double[rows][];
  2. Arrays.setAll(m, i -> {
  3. double[] row = new double[cols];
  4. Arrays.fill(row, 1.0);
  5. return row;
  6. });

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:

确定