沿3D数组中的第三个轴计算2D数组的逆数而无循环

编程入门 行业动态 更新时间:2024-10-24 18:20:28
本文介绍了沿3D数组中的第三个轴计算2D数组的逆数而无循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个形状为(N, N, K)的数组A,我想计算另一个与B[:, :, i] = np.linalg.inv(A[:, :, i])形状相同的数组B.

作为解决方案,我看到了map和for循环,但是我想知道numpy是否提供了执行此功能的功能(我尝试过np.apply_over_axes,但似乎只能处理一维数组). /p>

带有for循环:

B = np.zeros(shape=A.shape) for i in range(A.shape[2]): B[:, :, i] = np.linalg.inv(A[:, :, i])

与map:

B = np.asarray(map(np.linalg.inv, np.squeeze(np.dsplit(A, A.shape[2])))).transpose(1, 2, 0)

解决方案

对于可逆矩阵M,我们具有inv(M).T == inv(M.T)(逆的转置等于转置的逆).

由于np.linalg.inv是可广播的,因此可以通过简单地转置A,调用inv并转置结果来解决您的问题:

B = np.linalg.inv(A.T).T

例如:

>>> N, K = 2, 3 >>> A = np.random.randint(1, 5, (N, N, K)) >>> A array([[[4, 2, 3], [2, 3, 1]], [[3, 3, 4], [4, 4, 4]]]) >>> B = np.linalg.inv(A.T).T >>> B array([[[ 0.4 , -4. , 0.5 ], [-0.2 , 3. , -0.125]], [[-0.3 , 3. , -0.5 ], [ 0.4 , -2. , 0.375]]])

您可以按预期检查B的值是否匹配A中的数组的倒数:

>>> all(np.allclose(B[:, :, i], np.linalg.inv(A[:, :, i])) for i in range(K)) True

I have an array A whose shape is (N, N, K) and I would like to compute another array B with the same shape where B[:, :, i] = np.linalg.inv(A[:, :, i]).

As solutions, I see map and for loops but I am wondering if numpy provides a function to do this (I have tried np.apply_over_axes but it seems that it can only handle 1D array).

with a for loop:

B = np.zeros(shape=A.shape) for i in range(A.shape[2]): B[:, :, i] = np.linalg.inv(A[:, :, i])

with map:

B = np.asarray(map(np.linalg.inv, np.squeeze(np.dsplit(A, A.shape[2])))).transpose(1, 2, 0)

解决方案

For an invertible matrix M we have inv(M).T == inv(M.T) (the transpose of the inverse is equal to the inverse of the transpose).

Since np.linalg.inv is broadcastable, your problem can be solved by simply transposing A, calling inv and transposing the result:

B = np.linalg.inv(A.T).T

For example:

>>> N, K = 2, 3 >>> A = np.random.randint(1, 5, (N, N, K)) >>> A array([[[4, 2, 3], [2, 3, 1]], [[3, 3, 4], [4, 4, 4]]]) >>> B = np.linalg.inv(A.T).T >>> B array([[[ 0.4 , -4. , 0.5 ], [-0.2 , 3. , -0.125]], [[-0.3 , 3. , -0.5 ], [ 0.4 , -2. , 0.375]]])

You can check the values of B match the inverses of the arrays in A as expected:

>>> all(np.allclose(B[:, :, i], np.linalg.inv(A[:, :, i])) for i in range(K)) True

更多推荐

沿3D数组中的第三个轴计算2D数组的逆数而无循环

本文发布于:2023-11-29 17:31:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647101.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   第三个   而无   组中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!