meshgrid numpy的功能

时间:2013-11-06 22:23:26

标签: python numpy

我有一个问题,我想将矩阵的行列式绘制为参数的函数,所以我有一个脚本

def f(x, y):

    DD = np.matrix([[0., 0.],[0., 0.]]) + 0.j
    omega = x + 1.j * y

    # set up dispersion matrix
    DD[0,0] = 1 + omega
    DD[1,0] = omega
    DD[0,1] = omega
    DD[1,1] = 1 - omega

    metric = np.linalg.det(DD)

    return metric

xx = np.arange(1., 2., 0.1)
yy = np.arange(1., 2., 0.1)

x, y = np.meshgrid(xx, yy)


FPlot = f(x, y)

plt.contourf(x, y, FPlot)
plt.show()

有一个类型错误,因为omega是一个meshgrid,我不能将它粘在矩阵中或计算行列式 - numpy要求矩阵中的标量。获得正确网格和评估决定因素的最佳方法是什么?

2 个答案:

答案 0 :(得分:3)

您可以使用np.frompyfunc

import numpy as np
import matplotlib.pyplot as plt

def f(x, y):

    DD = np.matrix([[0., 0.],[0., 0.]]) + 0.j
    omega = x + 1.j * y

    # set up dispersion matrix
    DD[0,0] = 1 + omega
    DD[1,0] = omega
    DD[0,1] = omega
    DD[1,1] = 1 - omega

    metric = np.linalg.det(DD)

    return metric
f = np.frompyfunc(f, 2, 1)

xx = np.arange(1., 2., 0.1)
yy = np.arange(1., 2., 0.1)
x, y = np.meshgrid(xx, yy)

FPlot = f(x, y)

plt.contourf(x, y, FPlot)  # Note that this is only using the real part of FPlot
plt.show()

enter image description here

答案 1 :(得分:3)

如果你拥有全新的numpy 1.8,你可以使用它的一个很酷的新功能:线性代数gufuncs。基本上,当您调用np.linalg.det时,它会为您传入的任何形状数组计算最后两个维度的行列式:

xx = np.arange(1., 2., 0.1)
yy = np.arange(1., 2., 0.1)

x, y = np.meshgrid(xx, yy)
omega = x + 1.j * y

dispersion_matrices = np.empty(omega.shape + (2, 2), dtype=omega.dtype)
dispersion_matrices[..., 0, 0] = 1 + omega
dispersion_matrices[..., 1, 0] = omega
dispersion_matrices[..., 0, 1] = omega
dispersion_matrices[..., 1, 1] = 1 - omega
FPlot = np.linalg.det(dispersion_matrices)

plt.contourf(x, y, FPlot.imag) # the part missing in unutbus's plot!
plt.show()

enter image description here