【问题标题】:How to append the first element of a matrix onto a list over a loop?如何通过循环将矩阵的第一个元素附加到列表中?
【发布时间】:2019-02-15 21:26:10
【问题描述】:

我有两个循环针对不同的 x 和 y 坐标运行,并且对于每个不同的 (x,y) 坐标,使用矩阵方法求解力 1 和力 2 的线性方程,即如果 Ax 找到 A 的倒数= C. 对于每个循环,它以矩阵形式给出答案,其中第一个元素是力 1,第二个元素是那些特定坐标处的力 2。这是我的代码:

import numpy as np
from scipy import linalg
def Force():
    Force1 = np.zeros((160,90))
    Force2 = np.zeros((160,90))
    for x in np.arange(0,16.1,0.1):
        for y in np.arange(1,9.1,0.1):
            l1 = np.hypot(x,y)
            l2 = np.hypot(15-x,y)
            A = np.array([[(x/l1),((x-15)/l2)],[(y/l1),(y/l2)]])
            c = np.array([[0],[70*9.81]])

            F = linalg.solve(A,c)
            Force1[x,y] = F[0]
            Force2[x,y] = F[1]
            print("Force 1 = {} \nForce 2 = {}\n".format(F[0], F[1]))

所以在每个点 (x,y) 处求解一个矩阵 [[Force 1],[Force 2]]。现在我想将所有 Force1(s) 附加到 Force1[x,y] 列表中,对于 Forces2(s) 也是如此,这样我就可以做

plt.imshow[Force1]
plt.imshow[Force2]

绘制 2 个热图。我该怎么做呢?

【问题讨论】:

  • 你的意思是 mylistF1 = [] mylistF2 = [] mylistF1.append(Force1[x,y]) mylistF2.append(Force2[x,y]) ??
  • 如果您的最终目标是获得 2 个热图,只需使用 plt.imshow(Force1)plt.imshow(Force2)
  • 我不明白你的问题,你已经有了你的力阵列。例如,只需输入plt.imshow(Force1)
  • 我不能,因为它不允许我,它给了我这个错误“只有整数、切片 (:)、省略号 (...)、numpy.newaxis (None ) 和整数或布尔数组是有效的索引”对于 Force1[x,y] = F[0]

标签: python arrays python-3.x matrix list-comprehension


【解决方案1】:

这解决了您的问题 - 您试图分配给浮点类型的 Force1Force2 中的索引。我已将 for 循环更改为使用 enumerate,并调整了分配,以便分配 F[0][0]F[1][0]

import numpy as np
from scipy import linalg
def Force():
    Force1 = np.zeros((160,90))
    Force2 = np.zeros((160,90))
    for i, x in enumerate(np.arange(0,16,0.1)):
        for j, y in enumerate(np.arange(1,9,0.1)):
            l1 = np.hypot(x,y)
            l2 = np.hypot(15-x,y)
            A = np.array([[(x/l1),((x-15)/l2)],[(y/l1),(y/l2)]])
            c = np.array([[0],[70*9.81]])

            F = linalg.solve(A,c)
            Force1[i, j] = F[0][0]
            Force2[i, j] = F[1][0]
#            print("Force 1 = {} \nForce 2 = {}\n".format(F[0], F[1]))
    plt.imshow(Force1)
    plt.show()
    plt.imshow(Force2)
    plt.show()

Force()

生成的图是:

【讨论】:

    猜你喜欢
    • 2021-11-24
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多