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;💈範例:
Last updated
Was this helpful?