矩阵

矩阵

矩阵乘法

AB != BA  不满足交换律(matrix(1x3) * matrix(3x1) = matrix(1x1)) !== matrix(3x1) * (matrix(1x3)) = matrix(3x3)

(AB)C = A(BC) 结合律

K(AB) = (kA)B 分配律

(AB)^T = B^TA^T

(M1M2Mn)^T = Mn^T...M1^T


vABC 行向量左乘
CBAv 列向量右乘
class Matrix {
    constructor(...components) {
        this.rows = components
    }
    columns() {
        // (M * N)^T = matirx(N * M)
        // const colLen = this.rows[0].length
        // const rowLen = this.rows.length
        // const newRows = []
        // for (let colIndex = 0; colIndex < colLen; colIndex++) {
        //     const rows = []
        //     for (let rowIndex = 0; rowIndex < rowLen; rowIndex++) {
        //         rows[rowIndex] = this.rows[rowIndex][colIndex]
        //     }
        //     newRows[colIndex] = rows
        // }
        // return newRows
        return this.rows[0].map((_, i) => this.rows.map(row => row[i]))
    }
    mult(other) {
        if (this.rows[0].length !== other.rows.length) {
            throw new Error('该矩阵的列数不等于给定矩阵的行数')
        }
        const sum  = arr => arr.reduce((el, next) => el + next, 0)
        // 将矩阵转置
        const columns = other.columns()
        const newRows = this.rows.map(row => (
            columns.map(column => (
                sum(row.map((element, i) => element * column[i]))
            ))
        ))

        return new Matrix(...newRows)
    }
    transpose(){
        return new Matrix(...this.columns())
    }
    scaleMult(number){
        const newRows = this.rows.map(row => (
            row.map(element => element * number)
        ))
        return new Matrix(...newRows)
    }
}

const log = console.log

const one = new Matrix(
    [3, -1, 4],
  )
  const other = new Matrix(
    [-2, 0, 3],
    [5,  7, -6],
    [1,  -4, 2]
  )
log(one.transpose())

// const one = new Matrix(
//     [1, -5, 3],
//     // [0, -2, 6],
//     // [7, 2, -4],
//   )
//   const other = new Matrix(
//     [-8, 6, 1],
//     [7,  0, -3],
//     [2,  4, 5]
//   )

//   log(one.mult(other))
//   log(one.scaleMult(2))
//   log(one.transpose())

// const one = new Matrix(
//   [3, -4],
//   [0, -3],
//   [6, -2],
//   [-1, 1]
// )
// const other = new Matrix(
//   [3,  2, -4],
//   [4, -3,  5]
// )
// log(one.mult(other))
原文地址:https://www.cnblogs.com/pluslius/p/13817654.html