使用 NumPy 实现三对角矩阵算法 (TDMA)
我正在使用 NumPy 在 Python 中实现 TDMA。三对角矩阵存储在三个数组中:
a = array([...])
b = array([...])
c = array([...])
我想有效地计算 alpha 系数。算法如下:
# n = size of the given matrix - 1
alpha = zeros(n)
alpha[0] = b[0] / c[0]
for i in range(n-1):
alpha[i+1] = b[i] / (c[i] - a[i] * alpha[i])
但是,由于 Python 的 for
循环,这种方法效率不高。我想要的是这样的方法:
# n = size of the given matrix - 1
alpha = zeros(n)
alpha[0] = b[0] / c[0]
alpha[1:] = b[1:] / (c[1:] - a[1:] * alpha[:-1])
在后一种情况下,结果不正确,因为 NumPy 将最后一个表达式的右侧部分存储在临时数组中,然后将对其元素的引用分配给 alpha[1:]。因此 a[1:] * alpha[:-1]
只是一个零数组。
有没有办法告诉 NumPy 使用在其内部循环中先前步骤计算出的 alpha 值?
谢谢。
I'm implementing TDMA in Python using NumPy. The tridiagonal matrix is stored in three arrays:
a = array([...])
b = array([...])
c = array([...])
I'd like to calculate alpha
-coefficients efficiently. The algorithm is as follows:
# n = size of the given matrix - 1
alpha = zeros(n)
alpha[0] = b[0] / c[0]
for i in range(n-1):
alpha[i+1] = b[i] / (c[i] - a[i] * alpha[i])
However, this is not efficient because of Python's for
loop. Want I want is something like this approach:
# n = size of the given matrix - 1
alpha = zeros(n)
alpha[0] = b[0] / c[0]
alpha[1:] = b[1:] / (c[1:] - a[1:] * alpha[:-1])
In this latter case the result is incorrect because NumPy stores the right part of the last expression in a temprorary array and then assigns references to its elements to alpha[1:]
. Therefore a[1:] * alpha[:-1]
is just an array of zeros.
Is there a way to tell NumPy to use values of alpha
calculated on previous steps within its internal loop?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想求解三对角系统,可以在
numpy.linalg
中使用solve_banded()
。不确定这是否是您要找的。If its tridiagonal systems you want to solve there is
solve_banded()
innumpy.linalg
. Not sure if that's what you're looking for.显然,如果不使用 C 或其pythonic变体,就无法在 Python 中做到这一点。
Apparently, there is no way to do this in Python without using C or its pythonic variations.