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