简体   繁体   中英

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:

    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
  • start with a small letter for variables
  • java-style array declaration is of form 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. One thing you must note that you can't redefine X everytime you put something in it. You define it once and stick with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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