java multi-dimensional array transposing
I saw that all of the answers create a new resultant matrix. This is simple: matrix[i][j] = matrix[j][i];
However, you can also do this in-place, in case of square matrix.
// Transpose, where m == n
for(int i = 0; i < m; i++) {
for(int j = i+1; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
This is better for larger matrices, where creating a new resultant matrix is wasteful in terms of memory. If its not square, you can create a new one with NxM dimensions and do the out of place method. Note: for in-place, take care of j = i+1; Its not 0.
try this:
@Test
public void transpose() {
final int[][] original = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
for (int i = 0; i < original.length; i++) {
for (int j = 0; j < original[i].length; j++) {
System.out.print(original[i][j] + " ");
}
System.out.print("\n");
}
System.out.print("\n\n matrix transpose:\n");
// transpose
if (original.length > 0) {
for (int i = 0; i < original[0].length; i++) {
for (int j = 0; j < original.length; j++) {
System.out.print(original[j][i] + " ");
}
System.out.print("\n");
}
}
}
output:
1 2 3 4
5 6 7 8
9 10 11 12
matrix transpose:
1 5 9
2 6 10
3 7 11
4 8 12
I´m just digging this thread up because i did not find a working solution in the answers, therefore i will post one to help anyone who searches for one:
public int[][] transpose (int[][] array) {
if (array == null || array.length == 0)//empty or unset array, nothing do to here
return array;
int width = array.length;
int height = array[0].length;
int[][] array_new = new int[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
array_new[y][x] = array[x][y];
}
}
return array_new;
}
you should call it for example via:
int[][] a = new int[][] {{1,2,3,4},{5,6,7,8}};
for (int i = 0; i < a.length; i++) {
System.out.print("[");
for (int y = 0; y < a[0].length; y++) {
System.out.print(a[i][y] + ",");
}
System.out.print("]\n");
}
a = transpose(a); // call
System.out.println("");
for (int i = 0; i < a.length; i++) {
System.out.print("[");
for (int y = 0; y < a[0].length; y++) {
System.out.print(a[i][y] + ",");
}
System.out.print("]\n");
}
which will as expected output:
[1,2,3,4,]
[5,6,7,8,]
[1,5,]
[2,6,]
[3,7,]
[4,8,]