2016-03-04 75 views
2

我很難在python中插入矩陣/數據幀。Python:是否可以在MATLAB風格中插入矩陣?

假設我們我有一個矩陣M = 3x4x = [1 3 5]y = [0.1 0.4 0.5 0.7]

這是我的方式做插值,然後在Matlab繪製。

xq = 1:1:5; 
yq = 0.1:0.1:1; 
[xq,yq] = meshgrid(xq,yq); 
zq = interp2(y,x,M,xq,yq); 
figure 
h=pcolor(xq,yq,zq) 
set(h,'EdgeColor','none') 

這是在Python

from scipy import interpolate 
import numpy as np 

def my_interp(X, Y, Z, x, y, spn=3): 
    xs,ys = map(np.array,(x,y)) 
    z = np.zeros(xs.shape) 
    for i,(x,y) in enumerate(zip(xs,ys)): 
     # get the indices of the nearest x,y 
     xi = np.argmin(np.abs(X[0,:]-x)) 
     yi = np.argmin(np.abs(Y[:,0]-y)) 
     xlo = max(xi-spn, 0) 
     ylo = max(yi-spn, 0) 
     xhi = min(xi+spn, X[0,:].size) 
     yhi = min(yi+spn, Y[:,0].size) 
     # make slices of X,Y,Z that are only a few items wide 
     nX = X[xlo:xhi, ylo:yhi] 
     nY = Y[xlo:xhi, ylo:yhi] 
     nZ = Z[xlo:xhi, ylo:yhi] 
     intp = interpolate.interp2d(nX, nY, nZ) 
     z[i] = intp(x,y)[0] 
    return z 

zq = my_interp(y, x, M, xq, yq) 
+0

是的,有:) –

+1

一些公然的自我推銷:[插值(尋找griddata)](http://stackoverflow.com/questions/34643642/scipy-interp2d-bisplrep-unexpected-output-when-given -1d-input/34656728#34656728)和[pcolor(mesh)](http://stackoverflow.com/questions/35162798/superimpose-heat-maps-in-one-plot-in-python/35166749#35166749)。必要的功能是有據可查的。 –

+0

您可能會描述那些不熟悉MATLAB功能的Python人員的過程和結果。 – Prune

回答

3

一個可行的辦法正如我在評論所指出的,你的代碼是1:1的翻譯使用必要的庫到Python。您需要numpy代替linspace/meshgrid,matplotlib.pyplot代表pcolor(mesh),scipy.interpolate代表griddata。我想說的是「interp2d is available but don't use it,但事實證明,你需要在輸入數據的凸包外面進行推斷,所以griddata不會削減它。下面是interp2d的解決方案,但可以得到一些結果:

import numpy as np 
import scipy.interpolate as interp 
import matplotlib.pyplot as plt 

# input 
xv = np.array([1, 3, 5]) 
yv = np.array([0.1, 0.4, 0.5, 0.7]) 
x,y = np.meshgrid(xv,yv) 
M = np.random.rand(4,3) 

xqv = np.arange(1,6) 
yqv = np.arange(0.1,1.1,0.1) 
xq,yq = np.meshgrid(xqv,yqv) 
zqfun = interp.interp2d(x,y,M) 
zq = zqfun(xqv,yqv) 

plt.figure() 
#h = plt.pcolor(xq,yq,zq) 
h = plt.pcolormesh(xq,yq,zq) # <-- same thing but faster 

結果(左)與您的MATLAB原來相比(右;固定順序x,y,Minterp2d後):

resultmatlab original

你可以看到,結果在雙方有所不同,這是因爲MATLAB總是拋棄數據的最後一行和一列,而matplotlib沒有。