数组的转置,就是将原有数组所有元素的行号与列号进行交换,重新生成一个新的数组。
本文实现一个简单的矩阵转置demo,
先定义一个Marix类,然后定了若干变量,通过方法transpose来实现对矩阵的转置。
使用方法,将矩阵m传入构造函数进行实例化对象,然后调用transpose方法,结果返回转置矩阵mAT
class Marix {
m = [] //矩阵
colsNum //列号
rowsNum //行号
constructor(m) {
this.m = m
this.colsNum = this.getColsNum()
this.rowsNum = this.getRowsNum()
}
getRowsNum() {
return this.m.length
}
getColsNum() {
return this.m[0].length
}
transpose() {
let mAT = []
for (let j = 0; j < this.colsNum; j++) {
mAT[j] = []
for (let i = 0; i < this.rowsNum; i++) {
mAT[j][i] = this.m[i][j]
}
}
return mAT
}
}
export { Marix }