Unit 4 Cycle 2 Day 18: 2D Array: Matrix Transpose
Share
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.
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].