如何将稀疏的一维数组转换为二维数组?

问题描述 投票:0回答:1

我正在编写代码来求解2D热方程。我在x维度上有nx点,在y维度上有ny点。 (nx和ny是用户输入)。该解决方案以形状数组(nx * ny,)的形式出现。但是自然地,我想将解决方案绘制为2D阵列。因此,我尝试将结果的值分配给另一个2D数组,如下所示:

# A is a (nx*ny, nx*ny) sparse square matrix of csc format. b is a (nx*ny,) NumPy array.
y = sp.linalg.bicgstab(A, b)    # shape of y is (nx*ny,)
solution = np.zeros((nx, ny))
for i in range(0, ny):
    for j in range(0, nx):
        solution[i, j] = y[i + nx * j]

但是这会引发错误:

TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:/Users/USER/Desktop/Numerical Practice/FDM-2D Heat Equation-No Source.py", line 86, in <module>
    main()
  File "C:/Users/USER/Desktop/Numerical Practice/FDM-2D Heat Equation-No Source.py", line 77, in main
    solution[i, j] = y[i + nx * j]
ValueError: setting an array element with a sequence.

Process finished with exit code 1

我要去哪里错了,该怎么解决?我已经通过直接打印检查了初始结果(y)。 y正确显示。解决方案完成后,将发生错误。

P.S。如果我使用功能sp.linalg.spsolve而不是sp.linalg.bicgstab,则可以正常工作。但是我正在探索稀疏的迭代求解器,因此我想使用sp.linalg.bicgstab

python scipy sparse-matrix
1个回答
0
投票

我在官方文档中翻阅了。事实证明,所有的稀疏迭代求解器都返回两件事:解和收敛信息。如果仅将其写为y = sp.linalg.bicgstab(A, b),则y将变为形状(2,)的元组,其中第一个元素是解,第二个元素是会聚信息。我通过y, exit_code = sp.linalg.bicgstab(A, b)修复了它。现在可以正常使用

© www.soinside.com 2019 - 2024. All rights reserved.