numpy求解无循环的3d线性方程 [英] Numpy solving 3d linear equation without loop

查看:79
本文介绍了numpy求解无循环的3d线性方程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想求解线性方程Ax = b,每个A包含在3d矩阵中.例如

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

在Ax = B中, 假设A.shape为(2,3,3)

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

即= [[[1,2,3],[1,2,3],[1,2,3]] [[1,2,3],[1,2,3],[1,2,3 ]]]

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

并且B.shape为(3,1) 即[1,2,3] ^ T

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

我想知道Ax = B的每个3矢量 x ,即(x_1,x_2,x_3).

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

我想到的是将B与np.ones(2,3)相乘,然后将功能点与每个A元素的倒数一起使用.但这需要循环来完成.(矩阵尺寸增大时,这会花费大量时间)(例如A [:] [:] = [1,2,3]) 如何解决许多没有循环的Ax = B方程?

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?

  • 我使A和B的元素相同,但是您可能知道,这只是示例.

推荐答案

对于可逆矩阵,我们可以使用 np.linalg.inv ,然后将张量矩阵乘法与B一起使用,这样我们就失去了它们的最后一个轴和第一个轴分别是两个数组-

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)))

样品运行-

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)

在Python 3.x上,我们可以使用 @运算符具有相同功能-

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

np.linalg.inv(A) @ B

这篇关于numpy求解无循环的3d线性方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆