行列ライブラリ
numpy
これをサポートするモジュールを使用できます。
>>> import numpy as np
>>> a = np.matrix([[1, 2], [3, 4]])
>>> b = np.matrix([[2, 2], [2, 2]])
>>> a+b
matrix([[3, 4],
[5, 6]])
独自のソリューション: 重量級
自分で実装したいと仮定すると、次の機構をセットアップして、任意のペアワイズ操作を定義できるようにします。
from pprint import pformat as pf
class Matrix(object):
def __init__(self, arrayOfRows=None, rows=None, cols=None):
if arrayOfRows:
self.data = arrayOfRows
else:
self.data = [[0 for c in range(cols)] for r in range(rows)]
self.rows = len(self.data)
self.cols = len(self.data[0])
@property
def shape(self): # myMatrix.shape -> (4,3)
return (self.rows, self.cols)
def __getitem__(self, i): # lets you do myMatrix[row][col
return self.data[i]
def __str__(self): # pretty string formatting
return pf(self.data)
@classmethod
def map(cls, func, *matrices):
assert len(set(m.shape for m in matrices))==1, 'Not all matrices same shape'
rows,cols = matrices[0].shape
new = Matrix(rows=rows, cols=cols)
for r in range(rows):
for c in range(cols):
new[r][c] = func(*[m[r][c] for m in matrices], r=r, c=c)
return new
ペアワイズ メソッドの追加はパイと同じくらい簡単です。
def __add__(self, other):
return Matrix.map(lambda a,b,**kw:a+b, self, other)
def __sub__(self, other):
return Matrix.map(lambda a,b,**kw:a-b, self, other)
例:
>>> a = Matrix([[1, 2], [3, 4]])
>>> b = Matrix([[2, 2], [2, 2]])
>>> b = Matrix([[0, 0], [0, 0]])
>>> print(a+b)
[[3, 4], [5, 6]]
>>> print(a-b)
[[-1, 0], [1, 2]]
対累乗、否定、二項演算などを追加することもできます。行列の乗算と行列のべき乗のために * と ** を残すのがおそらく最善であるため、ここでは説明しません。
自家製のソリューション: 軽量
操作を 2 つのネストされたリスト マトリックスのみにマップする本当に簡単な方法が必要な場合は、次のようにします。
def listmatrixMap(f, *matrices):
return \
[
[
f(*values)
for c,values in enumerate(zip(*rows))
]
for r,rows in enumerate(zip(*matrices))
]
デモ:
>>> listmatrixMap(operator.add, a, b, c))
[[3, 4], [5, 6]]
追加の if-else とキーワード引数を使用すると、ラムダでインデックスを使用できます。enumerate
以下は、行列行順序関数の書き方の例です。わかりやすくするために、上記の if-else とキーワードは省略されています。
>>> listmatrixMap(lambda val,r,c:((r,c),val), a, indices=True)
[[((0, 0), 1), ((0, 1), 2)], [((1, 0), 3), ((1, 1), 4)]]
編集
add_matrices
したがって、上記の関数を次のように書くことができます。
def add_matrices(a,b):
return listmatrixMap(add, a, b)
デモ:
>>> add_matrices(c, d)
[[11, 4], [12, 6], [15, 19]]