2.4 矩阵ADT
矩阵是一个大小为m×n的数值表,包含如下方法:
- Matrix(rows, cols):创建一个rows×cols的矩阵,并将其内所有数值初始化为0;
- numRows():返回矩阵的行数;
- numCols():返回矩阵的列数;
- getitem(row, col):返回row行col列的数值;
- setitem(row, col, scalar):将row行col列的数值设定为scalar;
- scaleBy(scalar):数乘运算;
- tanspose():返回转置矩阵;
- add(other):加法;
- substract(other):减法;
- multiply(other):乘法。
加法和减法,数乘,乘法,转置,具体百度或Google就行。
2.4.2 矩阵的实现
#-*-coding: utf-8-*-
# 矩阵的实现
from myarray2d import Array2D
class Matrix(object):
def __init__(self, numRows, numCols):
self._theGrid = Array2D(numRows, numCols)
self._theGrid.clear(0) # 将矩阵中所有数初始化为零
def numRows(self):
return self._theGrid.numRows()
def numCols(self):
return self._theGrid.numCols()
def __getitem__(self, ndxTuple):
return self._theGrid[ndxTuple[0], ndxTuple[1]]
def __setitem__(self, ndxTuple, scalar):
self._theGrid[ndxTuple[0], ndxTuple[1]] = scalar
# 数乘运算
def scaleBy(self, scalar):
for r in range(self.numRows()):
for c in range(self.numCols()):
self[r, c] *= scalar
# 转置运算
def transpose(self):
newMatrix = Matrix(self.numCols(), self.numRows())
for i in range(self.numRows()):
for j in range(self.numCols()):
newMatrix[j, i] = self[i, j]
return newMatrix
# 矩阵加法
def __addd__(self, other):
assert other.numRows() == self.numRows() and other.numCols() == self.numCols(), "Matrix sizes not compatible for the add operation."
newMatrix = Matrix(self.numRows(), self.numCols())
for r in range(self.numRows()):
for c in range(self.numCols()):
newMatrix[r, c] = self[r, c] + other[r, c]
return newMatrix
# 矩阵减法
def __sub__(self, other):
assert other.numRows() == self.numRows() and other.numCols() == self.numCols(), "Matrix sizes not compatible for the substract operation."
newMatrix = Matrix(self.numRows(), self.numCols())
for r in range(self.numRows()):
for c in range(self.numCols()):
newMatrix[r, c] = self[r, c] - other[r, c]
return newMatrix
# 矩阵乘法
def __mul__(self, other):
assert other.numRows() == self.numCols(), "Matrix sizes not compatible for the multiple operation."
newMatrix = Matrix(self.numRows(), other.numCols())
for r in range(self.numRows()):
for c in range(other.numCols()):
newMatrix[r, c] = sum([self[r, i] * other[i, c] for i in range(self.numCols())])
return newMatrix