Sfitz12173 February 2016

Copying a 2D array into a 1D array

I have a 2D array of 7 rows by 5 cols. I am trying to convert the 2D array into a 1D array but for some reason it will only copy the last element in every row or the full last column.

My 2D array looks like this :

0   33  32  37  0 
85  73  82  73  80 
104 103 95  109 101 
88  108 111 116 100 
133 119 102 122 116 
116 123 95  112 117 
0   57  76  58  0 

But the output of my 1D array is:

0.0 80.0 101.0 100.0 116.0 117.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 .....

Here is my code :

public static void getTestImg() {
    TestImg = new double[35];
    double testValues;
    for (int r=0; r < TestPix.length; r++) {
        for (int c=0; c < TestPix[r].length; c++) {
            testValues = TestPix[r][c];
            TestImg[r] = testValues;
        }
    }
    for (int r=0; r < TestImg.length; r++) {
       System.out.print(TestImg[r] + " ");
    }
    System.out.println();
}

I've been trying to work out where I'm going wrong but I can't work out what is causing this. If I print "TestPix[r][c]" in the loop it is printing the elements in order so I don't know where the problem is. Can anyone help?

Answers


Eran February 2016

You are copying to the wrong index of the output array (r is the index of the current row of the source 2D array). You need a different index variable :

int x = 0;
for (int r=0; r < TestPix.length; r++) {
    for (int c=0; c < TestPix[r].length; c++) {
        TestImg[x++] = TestPix[r][c];
    }
}


Coder29 February 2016

Assuming its N*N matrix, you could do something like:

int N = board.length*board.length;
char[] board1D = new char[N];

int k = 0;
for (int i =0; i<board.length; i++) {
for (int j =0; j<board.length; j++) {
  board1D[k++] = board[i][j];
}
}


libik February 2016

You can use Eran solution, or this is also common way how to do it :

for (int r=0; r < TestPix.length; r++) {
    for (int c=0; c < TestPix[r].length; c++) {
        testValues = TestPix[r][c];
        TestImg[c + r*TestPix[r].length] = testValues;
    }
}

However this only works, if your array is rectangle (which in most cases is).

This is also "good to know", if you want count the index in 1D array with 2D indexes:

function index1D(int x, int y, int arrayColumnLength){
    return x*arrayColumnLength + y;
}

Post Status

Asked in February 2016
Viewed 2,800 times
Voted 8
Answered 3 times

Search




Leave an answer