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

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


# 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 正确输出。解决方案完成后出现错误。


PS 如果我使用函数sp.linalg.spsolve而不是sp.linalg.bicgstab,它工作正常。但我正在探索稀疏迭代求解器,所以我希望使用sp.linalg.bicgstab.


12345678_0001
浏览 127回答 2
2回答

红颜莎娜

您的代码有几个问题。触发您观察到的错误的那个是从返回值scipy.linalg.bicgstab()atuple而不是您期望的 NumPy 数组派生的。另一个问题是您尝试访问(nx, ny)索引i, j范围分别为0到ny和的形状对象nx。因此,除非您有nx == ny上面的代码,否则在某些时候会超出数组边界。最后,所有这些都是通过显式循环完成的。然而,NumPy 提供了更好的工具来获得你想要的东西,特别是np.reshape().例如:import numpy as npnx = 800ny = 1200y = np.random.randint(0, 100, nx * ny)def reshape_loops(y):&nbsp; &nbsp; solution = np.zeros((nx, ny))&nbsp; &nbsp; for i in range(0, nx):&nbsp; &nbsp; &nbsp; &nbsp; for j in range(0, ny):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; solution[i, j] = y[i + nx * j]&nbsp; &nbsp; return solutiondef reshape_np(y):&nbsp; &nbsp; return np.reshape(y.copy(), (nx, ny), order='F')print(np.allclose(reshape_loops(y), reshape_np(y)))# True%timeit reshape_loops(y)# 1 loop, best of 3: 319 ms per loop%timeit reshape_np(y)# 1000 loops, best of 3: 1.25 ms per loop矢量化方法快了约 250 倍。

明月笑刀无情

我在官方文档中四处寻找。事实证明,所有稀疏迭代求解器都会返回两件事:解和收敛信息。如果直接写成y = sp.linalg.bicgstab(A, b),y 就变成了一个形状为 (2,) 的元组,其中第一个元素是解,第二个元素是收敛信息。我通过这样做来修复它y, exit_code = sp.linalg.bicgstab(A, b)。现在它工作正常
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python