我用Fortran写了一个矩阵如下:
real(kind=kind(0.0d0)), dimension(256,256,256) :: dense
[...CALCULATION...]
inquire(iolength=reclen)dense
open(unit=8,file=fname,&
form='unformatted',access='direct',recl=reclen)
write(unit=8,rec=1)dense(:,:,:)
close(unit=8)
我想将其读回 Python。我所看到的一切都是针对 2D NxN 阵列而不是 3D 阵列。在 Matlab 中,我可以将其读作:
fid = fopen(nfilename,'rb');
mesh_raw = fread(fid,ndim*ndim*ndim,'double');
fclose(fid);
mesh_reshape = reshape(mesh_raw,[ndim ndim ndim]);
我只需要 Python 中的等效项——大概有一个类似的加载/ reshape 工具可用。如果有更友好的紧凑方式将其写出来供 Python 理解,我愿意接受建议。它可能看起来像this : 。我只是不熟悉我的案例的等效语法。一个好的引用就足够了。谢谢。
最佳答案
使用 IRO-bot 的链接,我为我的脚本修改/制作了这个(只是 numpy 魔法):
def readslice(inputfilename,ndim):
shape = (ndim,ndim,ndim)
fd = open(fname, 'rb')
data = np.fromfile(file=fd, dtype=np.double).reshape(shape)
fd.close()
return data
我对立方体进行了平均、最大、最小和求和,它与我的 Fortran 代码相匹配。感谢您的帮助。
关于python - 如何将输出的 Fortran 二进制 NxNxN 矩阵读入 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13827368/