如何使用matlab';fread&x27;用python?
这是一个 在Matlab中,我可以用这个代码来阅读如何使用matlab';fread&x27;用python?,python,matlab,Python,Matlab,这是一个 在Matlab中,我可以用这个代码来阅读 lonlatfile='NOM_ITG_2288_2288(0E0N)_LE.dat'; f=fopen(lonlatfile,'r'); lat_fy=fread(f,[2288*2288,1],'float32'); lon_fy=fread(f,[2288*2288,1],'float32')+86.5; lon=reshape(lon_fy,2288,2288); lat=reshape(lat_fy,2288,2288); 以下是M
lonlatfile='NOM_ITG_2288_2288(0E0N)_LE.dat';
f=fopen(lonlatfile,'r');
lat_fy=fread(f,[2288*2288,1],'float32');
lon_fy=fread(f,[2288*2288,1],'float32')+86.5;
lon=reshape(lon_fy,2288,2288);
lat=reshape(lat_fy,2288,2288);
以下是Matlab的一些结果:
如何在python中获得相同的结果
PS:我的代码是:
def fromfileskip(fid,shape,counts,skip,dtype):
"""
fid : file object, Should be open binary file.
shape : tuple of ints, This is the desired shape of each data block.
For a 2d array with xdim,ydim = 3000,2000 and xdim = fastest
dimension, then shape = (2000,3000).
counts : int, Number of times to read a data block.
skip : int, Number of bytes to skip between reads.
dtype : np.dtype object, Type of each binary element.
"""
data = np.zeros((counts,) + shape)
for c in range(counts):
block = np.fromfile(fid,dtype=np.float32,count=np.product(shape))
data[c] = block.reshape(shape)
fid.seek( fid.tell() + skip)
return data
fid = open(r'NOM_ITG_2288_2288(0E0N)_LE.dat','rb')
data = fromfileskip(fid,(2288,2288),1,0,np.float32)
loncenter = 86.5 #Footpoint of FY2E
latcenter = 0
lon2e = data+loncenter
lat2e = data+latcenter
Lon = lon2e.reshape(2288,2288)
Lat = lat2e.reshape(2288,2288)
但是,结果与Matlab不同。您应该能够将代码直接翻译成Python,而无需做任何更改:
lonlatfile = 'NOM_ITG_2288_2288(0E0N)_LE.dat'
with open(lonlatfile, 'rb') as f:
lat_fy = np.fromfile(f, count=2288*2288, dtype='float32')
lon_fy = np.fromfile(f, count=2288*2288, dtype='float32')+86.5
lon = lon_ft.reshape([2288, 2288], order='F');
lat = lat_ft.reshape([2288, 2288], order='F');
通常情况下,由于索引顺序不同,与MATLAB结果相比,numpy重塑将被转置。order='F'
部分确保最终输出与MATLAB版本具有相同的布局。它是可选的,如果您记得不同的索引顺序,您可以不使用它
将open()设为f:的
以安全的方式打开文件,确保在完成后再次关闭该文件,即使程序出现错误或由于任何原因被取消。严格地说,它不是必需的,但在打开文件时确实应该始终使用它。不同…如何?@excaza数组的相同位置具有不同的值。也许,你可以下载.dat文件并运行代码,将结果与matlab(我发布的图片)进行比较。@ZhangXin:然后请将答案标记为“正确”,以便其他人可以找到它。