#-*-encoding:utf-8-*-
"""
矩阵运算
"""
from vector import vector
class matrix(object):
def __init__(self, param = None):
"""
矩阵被定义为二维数组
>>> print(matrix())
[[]]
>>>
>>> print(matrix(1))
[[1]]
>>> print(matrix([1,2,3]))
[[1, 2, 3]]
>>> print(matrix([[1,2,3],[4,5,6],[7,8,9]]))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
"""
if not param:
self._data = [[]]
elif type(param) == type([]):
#如果传入一个列表,则当做一个单行向量处理
if len([True for element in param if type(element) not in [type(1), type(1.1), type('')]]) == 0:
self._data = [param]
else:
flag = []
for row in param:
for element in row:
if type(element) not in [type(1), type(1.1), type('')]:
flag.append(False)
if len(flag) == 0:
self._data = param
else:
raise RuntimeError("Wrong Element number:"+len(flag))
elif type(param) in [type(1), type(1.1), type('')]:
self._data = [[param]]
else:
raise TypeError("Input Param Error")
def __str__(self):
return(str(self._data))
def size(self):
"""
>>> print(matrix([[1,2,3],[4,5,6]]).size())
[2, 3]
>>> print(matrix([1,2,3]).size())
[1, 3]
>>> print(matrix(1).size())
[1, 1]
"""
rows = len(self._data)
cols = [len(row) for row in self._data]
if max(cols) == min(cols):
return([rows, min(cols)])
else:
return([rows, cols])
def __add__(self,anotherMatrix):
"""
>>> a=matrix(1)
>>> b=matrix(2)
>>> print(a+b)
[[3]]
>>> a=matrix([1,2,3])
>>> b=matrix([4,5,6])
>>> print(a+ b)
[[5, 7, 9]]
>>> a=matrix([[1,2,3],[4,5,6]])
>>> b=matrix([[2,3,4],[5,6,7]])
>>> print(a+b)
[[3, 5, 7], [9, 11, 13]]
"""
if self.size() != anotherMatrix.size():
raise RuntimeError("The tow matrixs have different size")
else:
result = []
size = self.size()
for i in range(size[0]):
row = []
for j in range(size[1]):
row.append(self._data[i][j] + anotherMatrix._data[i][j])
result.append(row)
return(matrix(result))
def __sub__(self,anotherMatrix):
"""
>>> a=matrix(1)
>>> b=matrix(2)
>>> print(a-b)
[[-1]]
>>> a=matrix([1,2,3])
>>> b=matrix([4,5,6])
>>> print(a-b)
[[-3, -3, -3]]
>>> a=matrix([[1,2,3],[4,5,6]])
>>> b=matrix([[2,3,4],[5,6,7]])
>>> print(b-a)
[[1, 1, 1], [1, 1, 1]]
"""
if self.size() != anotherMatrix.size():
raise RuntimeError("The tow matrixs have different size")
else:
result = []
size = self.size()
for i in range(size[0]):
row = []
for j in range(size[1]):
row.append(self._data[i][j] - anotherMatrix._data[i][j])
result.append(row)
return(matrix(result))
def __mul__(self,number):
"""
计算乘法
>>> matrix1=matrix([1,2,3])
>>> print(matrix1*2)
[[2, 4, 6]]
>>> print(matrix1*1.5)
[[1.5, 3.0, 4.5]]
"""
result = []
for row in self._data:
row = [element*number for element in row]
result.append(row)
return(matrix(result))
def __truediv__(self,number):
"""
计算除法
>>> matrix1=matrix([1,2,3])
>>> print(matrix1/2)
[[0.5, 1.0, 1.5]]
>>> print(matrix1/0)
Traceback (most recent call last):
...
ZeroDivisionError: int division or modulo by zero
"""
return(self*(1/number))
if __name__ == '__main__':
import doctest
doctest.testmod()