简体   繁体   English

如何在 java 中将三个数组转换为矩阵(二维数组)

[英]How to convert three array to a matrix(Two dimensional array) in java

I am going to convert three array as written in below into a Matrix (two dimensional array).我将把下面写的三个数组转换成一个矩阵(二维数组)。

Actually I do effort a lot but couldn't understand how to fill the matrix here is my code:实际上我做了很多努力但不明白如何填充矩阵这是我的代码:

double[] a1 = {2.1, 2.2, 2.3, 2.4, 2.5};
double[] a2 = {3.1, 3.2, 3.3, 3.4, 3.5};
double[] a3 = {4.1, 4.2, 4.3, 4.4, 4.5};

for(int i=0; i< a1.length; i++)
    {
       double[][] X = new double[i][3];
       for(int j=0; j<3; j++)
       {
                X[i][j] = "How should I fill the X Matrix";
       }

     }

I expected that my result should be like this我预计我的结果应该是这样的

        //       x1    x2     x3  
        X = { {  2.1,  3.1,  4.1 },
              {  2.2,  3.2,  4.2 },
              {  2.3,  3.3,  4.3 },
              {  2.4,  3.4,  4.4 },
              {  2.5,  3.5,  4.5 },
            }

You could put the ai -Arrays into a list and iterate over it to fill your 2d-array x as follows:您可以将ai -Arrays 放入一个列表并对其进行迭代以填充您的二维数组x ,如下所示:

    double[] a1 = {2.1, 2.2, 2.3, 2.4, 2.5};
    double[] a2 = {3.1, 3.2, 3.3, 3.4, 3.5};
    double[] a3 = {4.1, 4.2, 4.3, 4.4, 4.5};

    final List<double[]> aList = Arrays.asList(a1, a2, a3);

    double[][] x = new double[a1.length][3];
    for (int i = 0; i < a1.length; i++) {
      for (int j = 0; j < aList.size(); j++) {
        x[i][j] = aList.get(j)[i];
      }
    }

Remarks:评论:

  • initialize x outside of loop在循环外初始化x
  • start with a small letter for variables变量以小写字母开头
  • java-style array declaration is of form type[] name java 风格的数组声明的形式是type[] name

Here is a code that works:这是一个有效的代码:

        double a1[] = {2.1, 2.2, 2.3, 2.4, 2.5};
        double a2[] = {3.1, 3.2, 3.3, 3.4, 3.5};
        double a3[] = {4.1, 4.2, 4.3, 4.4, 4.5};
        double X[][] = new double[a1.length][3];
        for(int i=0; i< a1.length; i++){
                X[i][0] = a1[i];
                X[i][1] = a2[i];
                X[i][2] = a3[i];
        }
        for(int i = 0 ; i <a1.length ; i++){
            for(int j = 0 ; j < 3 ; j++){
                System.out.print(X[i][j] + " ");
            }
            System.out.println();
        }

I think it is pretty straightforward.我认为这很简单。 The thing is if you are going to do it for an arbitrary number of arrays then it won't work.问题是,如果您要对任意数量的 arrays 执行此操作,那么它将无法正常工作。 One thing you must note that you can't redefine X everytime you put something in it.您必须注意的一件事是,您不能每次将某些内容放入其中时都重新定义 X。 You define it once and stick with it.你定义它一次并坚持下去。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM