本文将介绍矩阵的大部分基本运算,其次是矩阵的加减运算、矩阵的标量乘法、矩阵与矩阵的乘法、求转置矩阵,并深入了解矩阵的行列式运算。本文不涉及逆矩阵和矩阵秩的概念,以后再讨论。
矩阵的加法和减法
的矩阵加减运算将接收两个矩阵作为输入,并输出一个新的矩阵。矩阵的加和减都是在组件级进行的,所以要加和减的矩阵必须有相同的维数。
为了避免重复加减法的代码,我们首先创建了一个可以接收运算函数的方法,它将对两个矩阵的分量分别执行一些传入运算。然后在加法、减法或其他运算中直接调用它:
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) { 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的反射变换:
调换
转置矩阵由公式定义。换句话说,我们通过翻转矩阵的对角线得到转置矩阵。请注意,矩阵对角线上的元素不受转置操作的影响。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 ZLME@xxxxxxxx@hotmail.com 举报,一经查实,立刻删除。