matlab读取fortran写的二进制文件

在科学计算中,经常有大量的数据要保存,这些计算程序很多是用Fortran写的,保存数据时为了占用更小的体积,更快的读写速度,避免浮点数精度损失,通常用二进制文件读写数据。而对数据进行分析时,又常常使用python,matlab等语言进行数据分析和可视化。这时候就要用matlab来读取fortran保存的二进制文件。

可以把数据写成matlab可以读取的形式,调用matlab读取数据的API.或者写成HDF5格式.或者直接用Fortran二进制写文件,用下面的方法读入matlab中.
Binary files that are generated by FORTRAN are quite different than ones that are expected by MATLAB. MATLAB expects a flat binary file. FORTRAN binary files are not flat.An unformatted FORTRAN binary file contains record length information along with each record. A record is a WRITE statement.The record length information is tagged on at the beginning and end of each record.
下面这段fortran代码有三个write语句,即文件中有三个记录(record),但是每个记录首尾会插入表示record长度信息的二进制数据。用matlab读取的时候要把这些长度信息去掉。

program wrt_bin
character*72 name
real*4 xsource, zsource, dt
integer*4    ntrace, nt
name='I am a genius groundhog!  Run!  Run!  Run!'
xsource=1.1
zsource=2.2
dt=3.3
ntrace=4
nt=5
open(unit=11, file='wrt_bin.bin', form='unformatted',
       +     status='new')
    WRITE(11) NAME
    WRITE(11) XSOURCE,ZSOURCE,DT
    WRITE(11) NTRACE,NT
close(11)
end

You will have to modify your MATLAb file to read out the record length information and access the data in which you are interested. An alternative would be to use the FSEEK() command in MATLAB to jump over the record length information and access the data directly.
Here is an example file that does so:

fid=fopen('wrt_bin.bin', 'rb'); 
fseek(fid, 4, 'cof'); 
name=setstr(fread(fid, 72, 'uchar'))';
fseek(fid, 4, 'cof'); 
fseek(fid, 4, 'cof'); 
xsource=fread(fid, 1, 'float32');
zsource=fread(fid, 1, 'float32'); 
dt=fread(fid, 1, 'float32'); 
fseek(fid, 4, 'cof');
fseek(fid, 4, 'cof'); 
ntrace=fread(fid, 1, 'int32'); 
nt=fread(fid, 1, 'int32');  
fclose(fid);
xsource, zsource, dt, ntrace, nt

fortran Stream Input/Output

事实上可以用流输出(stream output)去掉record length 信息
A binary file write adds extra record delimiters (hidden from programmer) to the beginning and end of recors. In fortran 2003, using access method 'stream' avoids this and implements a C-programming like approach:

REAL header(20), data(300)
OPEN(10,file="mydata.dat",access='stream')
WRITE(10) header
WRITE(10) data
CLOSE(10)

参考:
https://www.mathworks.com/matlabcentral/answers/97118-how-do-i-read-a-fortran-unformatted-binary-data-file-into-matlab

posted @ 2020-04-25 10:59  jun_phy  阅读(1513)  评论(0编辑  收藏  举报