【问题标题】:Creating 3d matrice from 2 lists从 2 个列表创建 3d 矩阵
【发布时间】:2020-08-19 09:52:24
【问题描述】:

我有两个值列表,xy

index = np.arange(-1,1,0.01)
x = index
y = index

在这个列表中,我想创建一个 3d 图,为此我需要 z,我目前有以下代码:

z = []
for i in x:
    temp_list = []
    for i2 in y:
        temp_list.append(-(i**2+i2**2))
    z.append(temp_list)

使用这些数据,我可以生成以下图表:

问题:

我如何生成形状为(len(x), len(y)) 的列表 z 仅使用 numpy 方法而不是使用此迭代,我在我的示例中这样做?

oneliners+1

【问题讨论】:

    标签: python python-3.x numpy matplotlib


    【解决方案1】:

    使用广播:

    import numpy as np
    
    index = np.arange(-1, 1, 0.1)
    
    Z = -(index[:,None] ** 2 + index[None, :] ** 2)
    

    这样可以避免使用np.meshgrid。如果轴不一样,你应该这样使用它:

    Z = -(x_axis[:,None] ** 2 + y_axis[None, :] ** 2)
    

    【讨论】:

      【解决方案2】:

      您可以使用numpy.meshgridindex 生成x-y 坐标:

      import numpy as np
      
      index = np.arange(-1, 1, 0.1)
      x, y = np.meshgrid(index, index)
      
      z = -(np.square(x) + np.square(y))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-14
        相关资源
        最近更新 更多