Perform Matrix Transpose in JavaScript
What you’ll learn
- What the transpose AT means: turn rows into columns so
(AT)ij = Aji. - How to implement it with a second buffer and nested loops in JavaScript.
- A 2×3 reference example (output shape 3×2), a 3×3 square example, plus a live preview and Try it (
target="_blank").
Overview
Transposing is one of the gentlest matrix operations: you copy each value from position (j, i) in the original into position (i, j) in the result. The grid “flips” so height and width swap.
Two programs
Rectangle 2×3 and square 3×3.
Live preview
Same numbers as the first program, computed in the browser.
Why a copy?
A separate array avoids stepping on values you still need while building the transpose.
Prerequisites
Nested loops and arrays of arrays (matrix[i][j]).
console.logand literals like[[1, 2, 3], [4, 5, 6]].- Knowing your
rowsandcols(or deriving them frommatrix.lengthandmatrix[0].lengthfor proper rectangles).
What is the transpose?
The transpose of a matrix A is written AT. Its entries satisfy (AT)ij = Aji: row and column indices are swapped.
So if A has m rows and n columns, AT has n rows and m columns.
Formal rule
For all valid indices, (AT)ij = Aji. Implementation-wise you often write transposed[i][j] = matrix[j][i] when i ranges over columns of the original and j over rows, matching the loop bounds below.
Live preview
Built-in 2×3 sample from example 1. Press the button to see A and AT.
Algorithm
Goal: given matrix with rows × cols, fill transposed with shape cols × rows using transposed[i][j] = matrix[j][i].
Allocate output shape
The result has cols rows and rows columns when the input has rows × cols.
Copy with swapped indices
Nested loops: for each i in 0 .. cols-1 and j in 0 .. rows-1, assign transposed[i][j] = matrix[j][i].
Print with outer loop over rows of the transposed matrix (length cols) and inner loop over columns (rows).
📜 Pseudocode
function transpose(matrix, rows, cols, out): // out is cols × rows
for i from 0 to cols - 1:
for j from 0 to rows - 1:
out[i][j] ← matrix[j][i]Transpose a 2×3 matrix (reference)
Classic layout: hold the original in a nested array, pass explicit rows and cols, build transposed with swapped dimensions. Also prints the original for context.
function transposeMatrix(matrix, rows, cols) {
const transposed = [];
let i, j;
for (i = 0; i < cols; i++) {
transposed[i] = [];
for (j = 0; j < rows; j++) {
transposed[i][j] = matrix[j][i];
}
}
console.log("Original (" + rows + " x " + cols + "):");
for (i = 0; i < rows; i++) {
let line = "";
for (j = 0; j < cols; j++) {
line += matrix[i][j] + "\t";
}
console.log(line);
}
console.log("");
console.log("Transposed Matrix (" + cols + " x " + rows + "):");
for (i = 0; i < cols; i++) {
let line = "";
for (j = 0; j < rows; j++) {
line += transposed[i][j] + "\t";
}
console.log(line);
}
}
const matrix = [
[1, 2, 3],
[4, 5, 6],
];
const rows = 2;
const cols = 3;
transposeMatrix(matrix, rows, cols);Explanation
The assignment transposed[i][j] = matrix[j][i] is the whole idea. Loop ranges follow the swapped dimensions: i runs cols times, j runs rows times.
Transpose a 3×3 matrix
Square example: first row 1 2 3 becomes the first column of the result. Still uses a separate buffer (simplest and safest for learners).
const N = 3;
function transposeSquare(a) {
const out = [];
let i, j;
for (i = 0; i < N; i++) {
out[i] = [];
for (j = 0; j < N; j++) {
out[i][j] = a[j][i];
}
}
return out;
}
function printMatrix(title, m) {
console.log(title);
let i, j;
for (i = 0; i < N; i++) {
let line = "";
for (j = 0; j < N; j++) {
line += m[i][j] + " ";
}
console.log(line);
}
}
const a = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const t = transposeSquare(a);
printMatrix("A", a);
console.log("");
printMatrix("A^T", t);Explanation
For square matrices, out is the same shape as a. In-place transpose (without extra memory) is possible for squares but easier to get wrong; two buffers keep the lesson clear.
Extensions
In place (square only). Swap a[i][j] with a[j][i] for i < j to avoid using a second matrix; watch indexing carefully.
Jagged vs rectangular. JavaScript arrays do not enforce uniform row length; validate every row before assuming matrix[0].length applies to all rows.
❓ FAQ
🔄 Input / output
To experiment, change the numbers inside matrix (and a in the square example) and adjust rows / cols so they stay consistent with how much of the structure you actually use.
Edge cases
Keep dimensions honest and guard against jagged rows.
rows and cols
They must match the slice of the nested arrays you filled. Wrong counts produce wrong output or runtime errors when indexing.
Jagged arrays
If rows have different lengths, matrix[j][i] may be undefined. Prefer validating rectangular input first.
⏱️ Time and space complexity
| Task | Time | Extra space |
|---|---|---|
Transpose m × n | O(m · n) | O(m · n) for the output buffer |
Summary
- Rule:
(AT)ij = Aji; sizes swap fromm×nton×m. - Code: copy into
transposed[i][j] = matrix[j][i]with matching loop bounds. - Double transpose:
(AT)T = A.
The transpose flips a matrix across its diagonal: rows become columns. If A is m × n, then AT is n × m, and (AT)T = A.
8 people found this page helpful
