Numpy solving 3d linear equation without loop

2019-02-26 00:16发布

I want solve linear equation Ax= b, each A contains in 3d matrix. For-example,

In Ax = B, Suppose A.shape is (2,3,3)

i.e. = [[[1,2,3],[1,2,3],[1,2,3]] [[1,2,3],[1,2,3],[1,2,3]]]

and B.shape is (3,1) i.e. [1,2,3]^T

And I want to know each 3-vector x of Ax = B i.e.(x_1, x_2, x_3).

What comes to mind is multiply B with np.ones(2,3) and use function dot with the inverse of each A element. But It needs loop to do this.(which consumes lots of time when matrix size going up high) (Ex. A[:][:] = [1,2,3]) How can I solve many Ax = B equation without loop?

  • I made elements of A and B are same, but as you probably know, it is just example.

1条回答
Animai°情兽
2楼-- · 2019-02-26 00:39

For invertible matrices, we could use np.linalg.inv on the 3D array A and then use tensor matrix-multiplication with B so that we lose the last and first axes of those two arrays respectively, like so -

np.tensordot( np.linalg.inv(A), B, axes=((-1),(0)))

Sample run -

In [150]: A
Out[150]: 
array([[[ 0.70454189,  0.17544101,  0.24642533],
        [ 0.66660371,  0.54608536,  0.37250876],
        [ 0.18187631,  0.91397945,  0.55685133]],

       [[ 0.81022308,  0.07672197,  0.7427768 ],
        [ 0.08990586,  0.93887203,  0.01665071],
        [ 0.55230314,  0.54835133,  0.30756205]]])

In [151]: B = np.array([[1],[2],[3]])

In [152]: np.linalg.solve(A[0], B)
Out[152]: 
array([[ 0.23594665],
       [ 2.07332454],
       [ 1.90735086]])

In [153]: np.linalg.solve(A[1], B)
Out[153]: 
array([[ 8.43831557],
       [ 1.46421396],
       [-8.00947932]])

In [154]: np.tensordot( np.linalg.inv(A), B, axes=((-1),(0)))
Out[154]: 
array([[[ 0.23594665],
        [ 2.07332454],
        [ 1.90735086]],

       [[ 8.43831557],
        [ 1.46421396],
        [-8.00947932]]])

Alternatively, the tensor matrix-multiplication could be replaced by np.matmul, like so -

np.matmul(np.linalg.inv(A), B)

On Python 3.x, we could use @ operator for the same functionality -

np.linalg.inv(A) @ B
查看更多
登录 后发表回答