📅  最后修改于: 2023-12-03 14:56:30.215000             🧑  作者: Mango
在编程中,矩阵转置是将矩阵的行和列交换的操作。在 JavaScript 中,我们可以使用多种方法来实现矩阵转置。
function transposeMatrix(matrix) {
const rows = matrix.length;
const columns = matrix[0].length;
// 创建一个新的矩阵来存储转置后的结果
const transposedMatrix = [];
// 初始化转置后的矩阵
for (let i = 0; i < columns; i++) {
transposedMatrix[i] = new Array(rows);
}
// 执行转置操作
for (let i = 0; i < rows; i++) {
for (let j = 0; j < columns; j++) {
transposedMatrix[j][i] = matrix[i][j];
}
}
return transposedMatrix;
}
使用示例:
const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const transposedMatrix = transposeMatrix(matrix);
console.log(transposedMatrix);
输出:
[ [ 1, 4, 7 ], [ 2, 5, 8 ], [ 3, 6, 9 ] ]
function transposeMatrix(matrix) {
return matrix[0].map((col, i) => matrix.map(row => row[i]));
}
使用示例:
const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const transposedMatrix = transposeMatrix(matrix);
console.log(transposedMatrix);
输出:
[ [ 1, 4, 7 ], [ 2, 5, 8 ], [ 3, 6, 9 ] ]
function transposeMatrix(matrix) {
return matrix.reduce((prev, next) =>
next.map((item, i) => (prev[i] || []).concat(next[i])), []);
}
使用示例:
const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const transposedMatrix = transposeMatrix(matrix);
console.log(transposedMatrix);
输出:
[ [ 1, 4, 7 ], [ 2, 5, 8 ], [ 3, 6, 9 ] ]
上述是三种常用的方法,你可以根据自己的需求选择合适的方法来实现矩阵转置。希望对你有所帮助!