Skip to content

← Tensor Foundations step 3 of 7

Easy Framework

Transpose a Matrix

A matrix transpose exchanges rows and columns. Input row i becomes output column i: output[j, i] = x[i, j].

Your task

Implement transpose(x) for a two-dimensional tensor of shape (m, n). Return shape (n, m), preserving the values, dtype and device. Leave x unchanged. No batched or higher-dimensional transpose is needed.

For x=[[1, 2, 3], [4, 5, 6]], return [[1, 4], [2, 5], [3, 6]]. The first input row, [1, 2, 3], becomes the first output column.

Use x.T in either framework. PyTorch also provides x.transpose(0, 1); JAX provides jnp.transpose(x).

Changing the shape alone is not enough. Reshaping the example to (3, 2) would produce [[1, 2], [3, 4], [5, 6]], which is a different arrangement. A square matrix keeps its shape when transposed, but its off-diagonal values still exchange positions. Transposing twice restores the original matrix.