-1

I have a 2d matrix:

double[][] data = new data[1000][1000];

and a 1d array:

int[] ID_list;

I want to make a new matrix:

double[][] new_data;

that is indexed using ID_list: new_data[1] => data[ID_list[1]], new_data[2] => data[ID_list[2]], ...

How can I do that in Java in the most efficient way possible?

Sebas
  • 21,192
  • 9
  • 55
  • 109
Dang Manh Truong
  • 795
  • 2
  • 10
  • 35

1 Answers1

3

If the idea is to reorganize the data based on the index store in ID_list. Iterate this array.

double[][] new_data = new double[ID_list.length][];
for(int i = 0; i < ID_list.length; ++i){
    new_data[i] = data[ID_list[i]];
}

This would only duplicate the reference of the array, not the value itself so this won't double the memory usage.

Note : I used ID_list length to initialise the array, this will be better if you only need some column.

Edit :

Here is an example to show that a 2D arrays is simply a arrays of arrays.

int[][] original = {
    {1,2,3},
    {4,5,6}
};

int[][] copy = new int[1][];
copy[0] = original[0];

System.out.println(original[0]);
System.out.println(copy[0]);

System.out.println(Arrays.toString(original[0]));
System.out.println(Arrays.toString(copy[0]));
original[0][1] = 7;
System.out.println(Arrays.toString(original[0]));
System.out.println(Arrays.toString(copy[0]));

Will output

[I@3941a79c //change on each run
[I@3941a79c
[1, 2, 3] //original[0]
[1, 2, 3] //copy[0]
[1, 7, 3] //original[0] after the update
[1, 7, 3] //copy[0]

Here is the JSL about Arrays member. This can be interesting to read.

AxelH
  • 14,325
  • 2
  • 25
  • 55
  • Can you provide a link to the documentation to substantiate the answer? I'm not entirely convinced this method would only duplicate the reference of the array :( – Dang Manh Truong Apr 05 '17 at 12:42
  • @DangManhTruong Well, you can start here. [How is a two-dimensional array represented in memory in java?](http://stackoverflow.com/questions/27465449/how-is-a-two-dimensional-array-represented-in-memory-in-java). An 2D array is only a reference of 1D arrays. It is easy to check, update a cell in the initial array, see the corresponding value in the new array (based on the ordering). It will be updated. – AxelH Apr 05 '17 at 12:47
  • But it does not say that the array will not be copied by value ? :( – Dang Manh Truong Apr 05 '17 at 13:47
  • @DangManhTruong Then you didn't read the post and didn't write a small test code. See the code I have added. If this is still not enough, I can't help you... – AxelH Apr 05 '17 at 13:56
  • Thank you, the code was very helpful. And in the link you provided, there is this line: "A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared. " . So I guess it's true then :P – Dang Manh Truong Apr 06 '17 at 12:42