除上述内容外,我还注意到here 关于对矩阵进行基本运算。这样做似乎总是很尴尬,你可能会写一些东西来帮助你在学习如何使用矩阵时更自然地工作。这是一个do 例程,它可能是一个帮助或如何编写自己的建议:
def do(self, s, i, j, k=1):
"""return self after doing row (`s` starts with 'r') or column (`s` starts with 'c') operation.
Examples
========
>>> from sympy import Matrix
>>> Matrix.do = do
>>> m = Matrix(3, 3, list(range(9))); m
Matrix([
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
swap rows 0 and 1
>>> m.do('rs',0,1)
Matrix([
[3, 4, 5],
[0, 1, 2],
[6, 7, 8]])
To row 0, add row 1 multiplied by 2
>>> m.do('ra',0,1,2)
Matrix([
[6, 9, 12],
[3, 4, 5],
[6, 7, 8]])
Multiply row 0 by 2
>>> m.do('rm',0,2)
Matrix([
[0, 2, 4],
[3, 4, 5],
[6, 7, 8]])
To operate on columns, replace the 'r' with 'c' in the
examples above.
If you want to keep working with the modified matrix
you can either re-assign the output to the variable used for
the original matrix (e.g. `m = m.do('rs', 0, 1)`) or make the
modifications in place by appending an 'i' to `s`:
>>> m.do('rsi',0,1)
>>> m
Matrix([
[3, 4, 5],
[0, 1, 2],
[6, 7, 8]])
>>> m.do('csi',0,1)
>>> m
Matrix([
[4, 3, 5],
[1, 0, 2],
[7, 6, 8]])
"""
rc, op = s.lower()[:2]
assert op in 'sma'
assert rc in 'rc'
if len(s) > 2:
# in place
if rc == 'r':
if op == 's':
self.row_swap(i,j)
elif op == 'm':
self.row_op(i, lambda v, _: v*j)
else:
self.row_op(i, lambda v, _: v + self[j, _]*k)
else:
if op == 's':
self.col_swap(i,j)
elif op == 'm':
self.col_op(i, lambda v, _: v*j)
else:
self.col_op(i, lambda v, _: v + self[_, j]*k)
else:
f = getattr(self, 'elementary_%s_op' % (
'row' if rc=='r' else 'col'))
if op == 's':
return f('n<->m', None, None, i, j)
elif op == 'a':
return f('n->n+km', None, k, i, j)
else:
return f('n->kn', i, j)