mat.transpose()
zip array of rows into array of columns.
*zip() is like the transpose of a matrix.
⭐️ 注意:原矩陣各列的長度可以不一樣,但經過 transpose() 後「各行」(也就是新矩陣的各列)長度都一樣,只是可能有些元素會是 undefined❗️
replit ⟩ zip(arrays)
/**
* see the matrix in "columns".
* @example
* let m = [[1,2], [3], [5,6]];
* m.transpose(); // [[1,3,5], [2,undefined,6]]
* @return {[[*]]} array of "columns"
*/
const matrix_transpose = {
/**
* see the matrix in "columns".
* - Note: may contain `undefined` elements if row lengths are different
* @example
* let m = [[1,2], [3], [5,6]];
* m.transpose(); // [[1,3,5], [2,undefined,6]]
* @return {[[*]]} array of "columns"
*/
transpose() {
return Array.from(
{ length: Math.max(...this.map(row => row.length)) }, // number of columns
(_, j) => this.map(row => row[j]) // for each row, choose jth column
)
}
};
export default matrix_transpose;
💈範例:
import matrix_transpose from '/.../matrix_transpose.mjs';
Object.assign(Array.prototype, matrix_transpose);
let m1 = [[1, 2], [3, 4], [5, 6]];
// 1 2
// --- 1 | 2
// 3 4 --(transpose)--> 3 | 4 (see matrix in "columns")
// --- 5 | 6
// 5 6
let m2 = [[1, 2], [3], [5, 6]];
m1.transpose() // [[1,3,5], [2,4,6]]
m2.transpose() // [[1,3,5], [2,undefined,6]]
Last updated