本文将介绍矩阵的大部分基本运算,分别是矩阵的加法和减法、矩阵的标量乘法、矩阵与矩阵的乘法、寻找转置矩阵、深入理解矩阵的行列式运算。逆矩阵和矩阵秩的概念本文不涉及,以后再讨论。
矩阵的加法和减法
矩阵的加法和减法将接收两个矩阵作为输入,并输出一个新矩阵。矩阵的加和减是在组件级执行的,因此要加和减的矩阵必须具有相同的维数。
为了避免重复文佳百科中的加减法代码,我们首先创建一个可以接收运算函数的方法。此方法将分别对两个矩阵的分量执行传入操作。然后在加法、减法或者其他运算中直接调用:
class Matrix { // ... componentWiseOperation(func, { rows }) { const newRows = rows.map((row, i) => row.map((element, j) => func(this.rows[i][j], element)) ) return new Matrix(...newRows) } add(other) { return this.componentWiseOperation((a, b) => a + b, other) } subtract(other) { return this.componentWiseOperation((a, b) => a - b, other) }}const one = new Matrix( [1, 2], [3, 4])const other = new Matrix( [5, 6], [7, 8])console.log(one.add(other))// Matrix { rows: [ [ 6, 8 ], [ 10, 12 ] ] }console.log(other.subtract(one))// Matrix { rows: [ [ 4, 4 ], [ 4, 4 ] ] }复制代码
矩阵的标量乘法
矩阵的标量乘法类似于向量的缩放,即矩阵中的每个元素都乘以一个标量:
class Matrix { // ... scaleBy(number) { const newRows = this.rows.map(row => row.map(element => element * number) ) return new Matrix(...newRows) }}const matrix = new Matrix( [2, 3], [4, 5])console.log(matrix.scaleBy(2))// Matrix { rows: [ [ 4, 6 ], [ 8, 10 ] ] }复制代码
矩阵乘法
当两个矩阵A和B的维数相容时,这两个矩阵可以相乘。维数兼容是指A的列数与B的行数相同,矩阵的积AB是通过计算A的每行与矩阵B的每列的点积得到的:
class Matrix { // ... multiply(other) { if (this.rows[0].length !== other.rows.length) { &n嘉文社百科bsp; throw new Error(\'The number of columns of this matrix is not equal to the number of rows of the given matrix.\') } 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) }}const one = new Matrix( [3, -4], [0, -3], [6, -2], [-1, 1])const other = new Matrix( [3, 2, -4], [4, -3, 5])console.log(one.multiply(other))// Matrix {// rows:// [ [ -7, 18, -32 ],// [ -12, 9, -15 ],// [ 10, 18, -34 ],// [ 1, -5, 9 ] ]}复制代码
我们可以把矩阵乘法AB看成是连续应用两个线性变换矩阵A和B。为了更好地理解这个概念,请看一下我们的线性代数演示。
下图中的黄色部分是对红色方块应用线性变换C的结果。线性变换C是矩阵乘法AB的结果,其中A是相对于Y轴反射的变换矩阵,B是剪切变换矩阵。
如果在矩阵乘法中改变A和B的顺序,会得到不同的结果,因为这相当于先应用B的剪切变换,再应用A的反射变换:
调换
转置矩阵由一个公式定义。换句话说,我们翻转矩阵的对角线,得到转置矩阵。注意,矩阵对角线上的元素不受转置操作的影响。
以上就是由优质生活领域创作者 嘉文社百科网小编 整理编辑的,如果觉得有帮助欢迎收藏转发~
本文地址:https://www.jwshe.com/683015.html,转载请说明来源于:嘉文社百科网
声明:本站部分文章来自网络,如无特殊说明或标注,均为本站原创发布。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。分享目的仅供大家学习与参考,不代表本站立场。