Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Matrix Transpose in C
Swap rows and columns with two nested loops, learn the in-place trick for square matrices, and see where transposing shows up in embedded C programming.
Matrix Transpose in C: What It Means
A matrix transpose in C is a new 2D array whose rows are the columns of the original. If the input has M rows and N columns, the output has N rows and M columns, and the element at [i][j] moves to [j][i]. This lecture in our free C programming course shows both the simple copy method and the memory-saving in-place method, with verified output you can reproduce. It is a compact way to practice index thinking, a skill the whole free embedded C course depends on.
What You Will Learn
- The definition of transpose and the resulting dimensions
- The one-line rule t[j][i] = m[i][j] and why the result array has swapped sizes
- A complete program with output for a non-square matrix
- The in-place swap for square matrices and why the inner loop starts at i + 1
- Where transposes appear in embedded C programming
- Typical bugs: double swapping, wrong result size
Prerequisites
You should have completed matrix addition and multiplication, and be able to swap two variables with a temporary. Any C11 compiler works.
Rows Become Columns
The transpose of a matrix is written with a small T, such as MT. The first row of the original becomes the first column of the result, the second row becomes the second column, and so on. Here is a 2×4 matrix and its 4×2 transpose:
Original 2×4 matrix and its 4×2 transpose
| Original m (2 rows, 4 cols) | Transpose t (4 rows, 2 cols) |
|---|---|
| 1 2 3 4 | 1 5 |
| 5 6 7 8 | 2 6 |
| 3 7 | |
| 4 8 |
Follow the number 7. In the original it sits at row 1, column 2. In the transpose it sits at row 2, column 1. Every element simply swaps its two indices, while the diagonal (where row equals column) stays where it is.
Index mapping for a few elements
| Value | Position in m | Position in t |
|---|---|---|
| 2 | m[0][1] | t[1][0] |
| 4 | m[0][3] | t[3][0] |
| 5 | m[1][0] | t[0][1] |
| 8 | m[1][3] | t[3][1] |
Method 1: Matrix Transpose in C with a Second Array
The straightforward approach reads each element of the source and writes it to the swapped position in a new array. The destination is declared with the dimensions reversed. Because source and destination are different arrays, there is no risk of overwriting data you still need, and this method works for any shape.
/* transpose.c - transpose a 2x4 matrix, then a 3x3 in place */
#include <stdio.h>
#define R 2
#define C 4
int main(void)
{
int m[R][C] = { {1, 2, 3, 4}, {5, 6, 7, 8} };
int t[C][R];
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
t[j][i] = m[i][j];
printf("transpose (%dx%d):\n", C, R);
for (int i = 0; i < C; i++) {
for (int j = 0; j < R; j++)
printf("%3d", t[i][j]);
printf("\n");
}
/* In-place transpose of a square matrix: swap above-diagonal pairs */
int sq[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
for (int i = 0; i < 3; i++)
for (int j = i + 1; j < 3; j++) {
int tmp = sq[i][j];
sq[i][j] = sq[j][i];
sq[j][i] = tmp;
}
printf("square in place:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
printf("%3d", sq[i][j]);
printf("\n");
}
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o transpose transpose.c
$ ./transpose
transpose (4x2):
1 5
2 6
3 7
4 8
square in place:
1 4 7
2 5 8
3 6 9
The key statement is t[j][i] = m[i][j];. Both loops still run over the source shape (R rows, C columns), while the assignment flips the indices on the destination. A frequent beginner error is to loop over the destination shape and then read from the wrong indices, which is why it helps to say the rule aloud: “row i, column j goes to row j, column i”.
Method 2: In-Place Transpose for Square Matrices
When the matrix is square (same number of rows and columns) you do not need a second array. Each pair of elements mirrored across the main diagonal just trades places. Look at the second half of the program above. The inner loop starts at j = i + 1, which visits only the cells above the diagonal. Each visit swaps sq[i][j] with its mirror sq[j][i].
Which cells are visited in a 3×3 in-place transpose
| Cell | col 0 | col 1 | col 2 |
|---|---|---|---|
| row 0 | diagonal, stays | swap with [1][0] | swap with [2][0] |
| row 1 | already swapped | diagonal, stays | swap with [2][1] |
| row 2 | already swapped | already swapped | diagonal, stays |
In-place transposing cannot work directly on a non-square matrix, because the shape itself changes (2×4 becomes 4×2), so the data no longer fits the same array declaration. Non-square in-place transposes exist, but they require reinterpreting a flat buffer with cycle-following logic, which is beyond this lecture.
| Method | Works for | Extra memory | Use when |
|---|---|---|---|
| Second array | Any M x N matrix | One full copy | Memory is available, or you need the original afterwards |
| In-place swap | Square N x N only | One temporary variable | RAM is tight and the original is no longer needed |
Matrix Transpose in Embedded C Programming
Why would firmware need a transpose? A few real situations:
- Display drivers: an LED matrix or an OLED page may expect data column by column, while your font table stores glyphs row by row. A transpose converts between the two.
- Keypad scanning: converting between a row-first table and a column-first table.
- Sensor arrays: data arrives channel-major but your filter wants sample-major.
- Linear algebra: many formulas, such as the least-squares solution, use MT times M.
A transposed read can also be done without copying anything: instead of building t, simply read m[j][i] where you would have read t[i][j]. That costs no memory, and it is often the smartest solution in a firmware loop. Build the physical copy only when a driver or library demands the new layout.
Performance Note
Writing t[j][i] in the inner loop jumps through memory one full row at a time, while the reads from m go in a straight line. On processors with a data cache, large transposes are therefore slower than they look, and blocked (tiled) algorithms exist to fix it. For the small matrices typical on a microcontroller this does not matter, but it explains an interview question you may be asked.
Common Mistakes and Troubleshooting
| Mistake | Symptom | Fix |
|---|---|---|
| Declaring the result as [R][C] | Compile warning or overwritten data for non-square input | Reverse the sizes: t[C][R] |
| Inner loop starts at 0 in the in-place version | Matrix unchanged | Start at j = i + 1 |
| Using in-place swapping on a non-square array | Wrong data or out-of-bounds access | Use a second array |
| Printing with the source dimensions | Missing or garbage rows | Print t with C rows and R columns |
| Forgetting the temporary in a swap | Both cells end up with the same value | Save one value in tmp first |
Best Practices
- Use named constants for sizes so the reversed declaration is obvious: t[C][R].
- Test with a non-square matrix, because a square test hides shape bugs.
- Check the property that transposing twice returns the original matrix.
- Prefer reading with swapped indices when you only need a transposed view.
- Comment the layout (row-major or column-major) wherever data crosses a driver boundary.
Summary and Key Takeaways
- Transpose swaps rows and columns: t[j][i] = m[i][j].
- An M x N matrix becomes N x M.
- A second array handles any shape; in-place swapping works only for square matrices.
- In the in-place loop the inner index starts at i + 1 to avoid swapping twice.
- A transposed view can often be achieved by just swapping the indices when reading.
Conclusion
The transpose is a small program with a big lesson: your data layout and your loops must agree about which index is the row and which is the column. In the final lecture of this array chapter we step one dimension higher with three-dimensional arrays, then close with a quiz and interview questions for this free embedded C course.
Frequently Asked Questions
What is the transpose of a matrix?
It is the matrix obtained by swapping rows and columns, so an element at [i][j] moves to [j][i].
What are the dimensions of the transpose of an M x N matrix?
The transpose has N rows and M columns.
Can I transpose a matrix without a second array?
Yes, but only when it is square. Swap each element above the diagonal with its mirror below the diagonal.
Why does the in-place loop start at j = i + 1?
To visit each mirrored pair once. Starting at 0 swaps every pair twice and restores the original matrix.
What happens to the diagonal elements in a transpose?
They stay where they are, because for them the row index equals the column index.
Do I always need to copy data to use a transpose?
No. You can often just read the original with the indices swapped, which costs no extra memory.
Free C Tutorial: Keep Learning
Next: three-dimensional arrays and memory layout. Follow the free C programming course on EmbeddedPathashala and turn embedded C programming basics into real skill.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments