Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #193 Transpose a two-dimensional matrix

Declare two two-dimensional arrays a and b of dimension n*m and m*n, respectively. Assign to b the transpose of a (i.e. the value with index interchange).

import static java.lang.reflect.Array.newInstance;
Class<?> c = a.getClass().getComponentType()
                         .getComponentType();
T b[][] = (T[][]) newInstance(c, m, n);
int y, x;
for (y = 0; y < m; ++y)
    for (x = 0; x < n; ++x)
        b[y][x] = a[x][y];
int b[][] = new int[m][n], x, y;
for (y = 0; y < m; ++y)
    for (x = 0; x < n; ++x)
        b[y][x] = a[x][y];
(def a [[1 2 3] [4 5 6] [7 8 9]])
(def b (apply (partial mapv vector) a))

New implementation...
< >
tkoenig