- What the transpose of a matrix is — and how it changes dimensions
- How to swap row and column indices in a 2D array operation
- Why the output matrix has dimensions
[COLS][ROWS], not[ROWS][COLS] - How to transpose a non-square matrix (where
ROWS ≠ COLS) - How the transpose is used in practice — dot products, symmetric matrices, matrix multiplication
What the transpose is
The transpose of a matrix is what you get when you "flip" it along its main diagonal — turning every row into a column, and every column into a row. If A has entries A[i][j] at row i, column j, then its transpose AT has entries AT[i][j] = A[j][i]. What was in row 0 becomes column 0, what was in column 1 becomes row 1, and so on.
A crucial property: the transpose changes the dimensions. If A is m × n (m rows, n columns), then AT is n × m. A 3×3 matrix stays 3×3 when transposed (same shape, different entries), but a 2×3 matrix becomes a 3×2 matrix. This is the trickiest part of the transpose in C: the output matrix has a different shape from the input. You can't just use the same-size matrix for both. You need a separate output with the dimensions swapped.
The transpose appears in many contexts. In linear algebra, it's used to define dot products, orthogonal matrices, symmetric matrices (A = AT), and the normal equations for least-squares fitting. In computer graphics, normal vectors are stored as matrices and transposed to compute lighting. In machine learning, weight matrices are transposed to align input features with output dimensions. In networking, data laid out row-major (a stream of bytes) is sometimes transposed to align with column-major expectations. It's a small operation with a lot of applications.
For a square matrix, the transpose can be done in place by swapping A[i][j] with A[j][i] for all i < j. For a non-square matrix, you need a separate output — the input can't hold the result because the shape changes. Our program uses the separate-output approach throughout, since it works for any shape and is simpler to reason about.
💡 In one line: for each cell of the input at (i, j), copy it to the output at (j, i). The output has dimensions [COLS][ROWS] — row and column counts are swapped.
Designing the transposeMatrix function
The signature requires careful attention to the dimensions — they're different between input and output:
| Part | Choice | Why |
|---|---|---|
| Function name | transposeMatrix | Descriptive. Alternatives: transpose, matrixTranspose. |
| Input | const int a[ROWS][COLS] | Read-only. Shape is ROWS × COLS. |
| Output | int result[COLS][ROWS] | Dimensions are swapped. The output is COLS × ROWS. |
| Return type | void | The result goes in the output parameter. |
The prototype:
#define ROWS 3
#define COLS 3
void transposeMatrix(const int a[ROWS][COLS], int result[COLS][ROWS]);
And the definition — the whole function is a nested loop with one swapped-index assignment:
void transposeMatrix(const int a[ROWS][COLS], int result[COLS][ROWS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
result[j][i] = a[i][j];
}
}
}
Three lines of logic. The outer loop goes over the input's rows; the inner loop goes over the input's columns. For each cell a[i][j], we copy it to result[j][i] — the indices are reversed. That's the entire transpose operation.
Notice how similar this is to matrix addition from the previous assignment. The differences are:
- One input instead of two.
- The output dimensions are swapped:
[COLS][ROWS]instead of[ROWS][COLS]. - The assignment uses
[j][i]on the destination instead of[i][j].
Everything else is the same: nested loops, iterate over all cells, one write per cell. That's the reuse of the pattern in action — once you've internalized matrix traversal, most matrix operations are small variations on the same theme.
For a non-square matrix — say, 2 rows and 3 columns — the same function works, but the output is 3 rows and 2 columns:
#define ROWS 2
#define COLS 3
void transposeMatrix(const int a[ROWS][COLS], int result[COLS][ROWS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
result[j][i] = a[i][j];
}
}
}
The only change is the #define values. The function body is identical — the loops and index swap are shape-agnostic. This is a nice property of the code: the logic doesn't care about dimensions, only the declarations do.
And here's an in-place version, only valid for square matrices:
void transposeInPlace(int a[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = i + 1; j < COLS; j++) {
int temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
}
This swaps a[i][j] with a[j][i] for all i < j, modifying the input in place. It works only for square matrices (since a[i][j] and a[j][i] must both exist). The inner loop starts at i + 1 — the diagonal stays put, and each pair is swapped only once (not twice). This is more memory-efficient but less general. Use it when you have a square matrix and want to avoid allocating a second buffer.
🎯 Key idea: the transpose swaps indices. On assignment: result[j][i] = a[i][j]. On function parameters: int a[ROWS][COLS] becomes int result[COLS][ROWS]. Both changes must happen — swapping only one leads to a shape mismatch or a wrong result.
Complete C Program
Program: read a 3×3 matrix, transpose it, print both
#include <stdio.h>
#define ROWS 3
#define COLS 3
/* Function prototypes */
void transposeMatrix(const int a[ROWS][COLS], int result[COLS][ROWS]);
void printMatrix(const int mat[][COLS], int rows, int cols, const char *name);
int main(void) {
int A[ROWS][COLS];
int T[COLS][ROWS];
printf("Enter matrix A (%d rows, %d columns):\n", ROWS, COLS);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (scanf("%d", &A[i][j]) != 1) return 1;
}
}
transposeMatrix(A, T);
printMatrix(A, ROWS, COLS, "A");
printMatrix(T, COLS, ROWS, "A^T (transpose)");
return 0;
}
void transposeMatrix(const int a[ROWS][COLS], int result[COLS][ROWS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
result[j][i] = a[i][j];
}
}
}
void printMatrix(const int mat[][COLS], int rows, int cols, const char *name) {
printf("\nMatrix %s:\n", name);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%5d", mat[i][j]);
}
printf("\n");
}
}
There's a subtlety in the printMatrix function: its parameter is const int mat[][COLS], which works for the original matrix (shape [ROWS][COLS]) but not for the transpose (shape [COLS][ROWS]). Since ROWS = COLS = 3 in this example, they happen to be compatible — but for a non-square matrix, you'd need two separate print functions or a more generic one. This is one of the awkward parts of 2D-array parameters in C: the inner dimension must be fixed, so a function that handles different inner dimensions must be written separately.
And here's a version that handles a non-square matrix — specifically, a 2×3 matrix and its 3×2 transpose:
Variant: non-square matrix (2×3 → 3×2)
#include <stdio.h>
#define ROWS 2
#define COLS 3
void transposeMatrix(const int a[ROWS][COLS], int result[COLS][ROWS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
result[j][i] = a[i][j];
}
}
}
int main(void) {
int A[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}};
int T[COLS][ROWS];
transposeMatrix(A, T);
printf("Matrix A (2×3):\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) printf("%4d", A[i][j]);
printf("\n");
}
printf("\nTranspose (3×2):\n");
for (int i = 0; i < COLS; i++) {
for (int j = 0; j < ROWS; j++) printf("%4d", T[i][j]);
printf("\n");
}
return 0;
}
This version is more illustrative of the transpose's power: a 2×3 matrix becomes a 3×2 one. The function body is identical to the square version — only the #define values and the print loops differ. That's the point: the transpose algorithm doesn't care about the shape; it just swaps indices.
And here's a version that uses transposeInPlace for a square matrix — more efficient, no second array needed:
Variant: in-place transpose for square matrices
#include <stdio.h>
#define N 3
void transposeInPlace(int a[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
int temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
}
int main(void) {
int A[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
transposeInPlace(A);
printf("Transposed in place:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) printf("%4d", A[i][j]);
printf("\n");
}
return 0;
}
The in-place version saves memory — one array instead of two — but only works for square matrices. The inner loop's start at i+1 is the trick: it skips the diagonal (each diagonal element stays put) and ensures each off-diagonal pair is swapped exactly once (not twice, which would undo the swap). This is the sort of careful loop bound that makes the difference between correct and buggy code.
Program Output
For the 3×3 example:
Enter matrix A (3 rows, 3 columns):
1 2 3
4 5 6
7 8 9
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix A^T (transpose):
1 4 7
2 5 8
3 6 9
The rows of A become the columns of AT: the first row (1 2 3) becomes the first column (1 4 7 — wait, that's the first column of AT). Let's check: A[0][0]=1 goes to AT[0][0]=1. A[0][1]=2 goes to AT[1][0]=2. A[0][2]=3 goes to AT[2][0]=3. Yes — the first row of A becomes the first column of AT. Correct.
For the 2×3 example:
Matrix A (2×3):
1 2 3
4 5 6
Transpose (3×2):
1 4
2 5
3 6
Notice the shape change — the input has 2 rows and 3 columns; the output has 3 rows and 2 columns. This is the essential feature of the transpose for non-square matrices. If you accidentally used the same dimensions for both matrices, you'd either overflow the output (if the input has more columns than rows) or leave cells unwritten (if it has more rows). The correct declaration is crucial.
And for the in-place version:
Transposed in place:
1 4 7
2 5 8
3 6 9
Same result as the separate-output version, but the original A is now the transpose. This works because the input and output are the same array, and the loop is structured to avoid double-swapping.
Step-by-Step Explanation
Let's trace the algorithm and understand why the index swap works.
1. The index swap: result[j][i] = a[i][j]
The heart of the transpose is this single line. For each cell (i, j) of the input, we write to cell (j, i) of the output. What was in row i, column j ends up in row j, column i — precisely the transpose operation. The two indices are swapped, and the operation is complete.
2. Why the output dimensions are reversed
If the input is m × n, then i ranges from 0 to m-1 and j ranges from 0 to n-1. The output cell result[j][i] has first index j (which can go up to n-1) and second index i (which can go up to m-1). So the output must be declared with the first dimension at least n and the second at least m. That's why the parameter is int result[COLS][ROWS], not int result[ROWS][COLS].
If you declared the output with the same dimensions as the input, two things could go wrong. If ROWS > COLS, you'd be writing to result[j][i] where i can exceed ROWS-1... wait, i is at most ROWS-1, which is fine for the second dimension if COLS ≥ ROWS. Let me re-check: if the input is 2 × 3 (ROWS=2, COLS=3), the output needs to be 3 × 2. If you declare the output as int result[2][3], then writing to result[j][i] with j up to 2 would overflow the first dimension (which only has indices 0 and 1). That's a buffer overflow — undefined behavior.
3. Tracing transposeMatrix for a 2×3 example
Input: A = {{1, 2, 3}, {4, 5, 6}}. Expected output: T = {{1, 4}, {2, 5}, {3, 6}}.
- i=0, j=0: result[0][0] = A[0][0] = 1.
- i=0, j=1: result[1][0] = A[0][1] = 2.
- i=0, j=2: result[2][0] = A[0][2] = 3.
- i=1, j=0: result[0][1] = A[1][0] = 4.
- i=1, j=1: result[1][1] = A[1][1] = 5.
- i=1, j=2: result[2][1] = A[1][2] = 6.
Six iterations, six cells filled in — the output matrix is fully populated. Result is {{1, 4}, {2, 5}, {3, 6}}, which is exactly the transpose. ✓
4. Why the transpose is a bijection
Every input cell maps to exactly one output cell, and every output cell is written exactly once. This is because the mapping (i, j) → (j, i) is a bijection on the set of index pairs (within the appropriate ranges). So the output is completely determined by the input — no cell is missed, no cell is overwritten. That's why the algorithm is correct and why the output array is fully filled.
5. The in-place version's subtlety
In the in-place version, the loop bound j = i + 1 is critical. If we started at j = 0, we'd swap A[i][j] with A[j][i] for all pairs, including when j < i. But those pairs are the same as swapping A[j][i] with A[i][j] — the operation would happen twice for each off-diagonal pair, and the two swaps would cancel out. The result would be the original matrix, unchanged.
Starting at j = i + 1 ensures each off-diagonal pair is swapped exactly once. The diagonal (when i == j) is skipped — swapping a value with itself is a no-op. The result is the transposed matrix, in place.
6. The transpose of a transpose
Applying the transpose twice gives you the original matrix: (AT)T = A. This is because swapping indices twice returns them to their original positions. This is a useful sanity check: if you transpose a matrix and then transpose the result, you should get back the input. Try it with the program — the double transpose should match the original.
7. The transpose and symmetric matrices
A matrix is symmetric if A = AT. Our program could be extended to check symmetry by comparing A with its transpose (element by element), or — more efficiently — by checking that A[i][j] == A[j][i] for all i < j. This is the next assignment (assignment 25), and it builds directly on this one. Once you can compute the transpose, checking symmetry is straightforward.
8. The transpose and dot products
If you store vectors as column matrices (n×1), then the transpose of a vector is a row matrix (1×n). The dot product of two vectors u and v is uT · v — a 1×n matrix times an n×1 matrix, giving a 1×1 matrix (a scalar). This is the mathematical foundation of machine learning's linear algebra: every neural network layer computes a matrix multiplication, and transposes are used to align dimensions. Understanding the transpose at the implementation level gives you insight into what these operations do on the CPU.
9. Complexity
O(ROWS × COLS) time — one copy per cell. O(ROWS × COLS) extra space for the output (in the non-in-place version), or O(1) extra space for the in-place version. Both are optimal — you can't transpose without touching each cell, and you can't avoid the extra space for a non-square matrix. For typical square matrices, the in-place version is more efficient; for non-square, the separate-output version is necessary.
10. When the transpose is useful
The transpose appears in many algorithms. In matrix multiplication, the inner loop often accesses columns of one matrix, which is cache-unfriendly in row-major storage — transposing the second matrix first can dramatically speed up the computation. In machine learning, weight matrices are often stored transposed to align with input feature layouts. In graphics, normal vectors and view matrices are transposed to compute lighting. In data processing, transposing a large row-major dataset to column-major (or vice versa) is a common operation. So while the transpose itself is small, it's a building block that shows up everywhere.
🔍 Try this: write a symmetric-check function that returns 1 if A == AT and 0 otherwise. It's a natural extension of this assignment, and it builds toward the next one. Then try a "skew-symmetric" check: A[i][j] = -A[j][i], and A[i][i] = 0 for the diagonal. Skew-symmetric matrices appear in physics (angular velocity, cross products) and are worth knowing about.
Frequently Asked Questions
1. Why does the output have different dimensions than the input?
Because the transpose swaps rows and columns. An m × n matrix has m rows and n columns; its transpose has n rows and m columns. This is fundamental to what the transpose means. For a square matrix (m = n), the dimensions happen to be the same, which is why the in-place version works for square but not non-square matrices. For non-square, you must allocate a separate output with swapped dimensions.
2. Why is the inner loop bound j < COLS and not j < ROWS?
Because we're iterating over the input matrix's cells. The outer loop i goes over the input's rows (0 to ROWS-1), and the inner loop j goes over the input's columns (0 to COLS-1). We're reading a[i][j], so both bounds match the input. The output indices are result[j][i] — the swap happens at the assignment, not in the loop bounds. If you accidentally used j < ROWS in the inner loop, you'd miss some cells or access out of bounds, depending on whether ROWS is less than or greater than COLS.
3. Can I transpose a matrix in place?
Only for square matrices. The in-place version swaps a[i][j] with a[j][i] for i < j, which works only if both indices are valid in the same array. For an m × n matrix with m ≠ n, a[j][i] might not be a valid cell (out of bounds), so the in-place swap would corrupt memory or crash. For non-square matrices, you must use a separate output with the correct swapped dimensions. In-place is more memory-efficient but less general.
4. How does the transpose relate to other matrix operations?
The transpose is a building block for many operations. In matrix multiplication, the formula C[i][j] = sum(A[i][k] * B[k][j]) can be rewritten using transposes: C = A * B where B is pre-transposed, or via C = (BT * AT)T. In solving linear equations, the normal equations involve transposes: ATAx = ATb. In linear algebra, the transpose defines orthogonality, symmetric matrices, and many other concepts. So while the transpose itself is simple, understanding it is a foundation for everything that comes after.
5. How does the transpose interact with matrix multiplication?
There's a useful identity: (AB)T = BT AT — the transpose of a product is the product of the transposes in reverse order. This is used all over in linear algebra: proving properties of symmetric matrices, simplifying matrix expressions, computing gradients in machine learning. The reversal of order is important — you can't just transpose both and multiply; you have to reverse them. It's a small detail that trips up beginners.
6. Can I use this to check if a matrix is symmetric?
Yes — a symmetric matrix is one where A = AT. After computing the transpose, compare each element: if A[i][j] == T[j][i] for all i, j (which is trivially true by construction), you'd actually be checking that A[i][j] == A[j][i] — that's the real condition. So a "symmetric check" would compare A[i][j] to A[j][i] directly, without needing a transpose matrix. That's the more efficient approach. The next assignment (25) covers this in detail.
💡 Tip: Once this works, try computing AT × A for a matrix A — the result is always symmetric (even if A itself isn't). This is called the Gram matrix, and it's used in least-squares fitting, principal component analysis, and other machine learning techniques. To compute it, you'd write three nested loops: C[i][j] = sum over k of AT[i][k] * A[k][j] = sum over k of A[k][i] * A[k][j]. Notice the symmetry in the formula — that's why the result is always symmetric. A great exercise in translating math into code.