Ali Mosavi
Ali Mosavi

Reputation: 23

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

Upvotes: 0

Views: 602

Answers (2)

Mahmood Darwish
Mahmood Darwish

Reputation: 546

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.

Upvotes: 0

Michael Kreutz
Michael Kreutz

Reputation: 1256

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

Upvotes: 1

Related Questions