Unit 4 Cycle 2 Day 18: 2D Array: Matrix Transpose

Unit 4 Advanced (Cycle 2) Day 18 of 28 Advanced

2D Array: Matrix Transpose

Section 4.11 — 2D Array Algorithms

Key Concept

Matrix transpose swaps rows and columns: element grid[r][c] moves to result[c][r]. For a square matrix, this can be done in-place by swapping elements across the diagonal. For non-square matrices, a new array with swapped dimensions is required. The AP exam tests transpose as a 2D array manipulation problem requiring nested loops. The key is getting the dimensions right: if the original is m * n, the transpose is n * m, and the loop bounds must reflect this.

Consider the following code segment.

int[][] mat = {{1, 2, 3}, {4, 5, 6}}; int[][] trans = new int[mat[0].length][mat.length]; for (int r = 0; r < mat.length; r++) for (int c = 0; c < mat[0].length; c++) trans[c][r] = mat[r][c]; System.out.println(trans.length + " " + trans[0].length);

What is printed?

Answer: (B) 3 2

Original is 2x3. Transpose swaps dimensions: 3x2. trans.length=3, trans[0].length=2.

Why Not the Others?

(A) 2 3 are the original dimensions.

(C) Not a square matrix.

(D) Would lose data.

Common Mistake

Transpose: trans[c][r] = mat[r][c]. Dimensions swap: rows become columns.

AP Exam Tip

Transpose of an m x n matrix is n x m. The key formula is trans[c][r] = original[r][c].

Review this topic: Section 4.11 — 2D Array Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.