How to read an N-dimensioned matrix from a binary file

9 ビュー (過去 30 日間)
Jim
Jim 2013 年 2 月 13 日
回答済み: Aniruddh Murali 2018 年 9 月 27 日
I would like to write a Matlab script to read an N-dimensioned matrix created in Fortran. Specifically, the Fortran code wrote to a binary file using the following:
write(30) a, b, c
with the following declarations for a,b,c
real a(16,20,22,6,3, 2)
real b(16,20,22,6,3,13)
real c(16,20,22,6,3,13)
In Matlab, it seems that fread handles only a vector or 2-dimesional matrix fread(fileID, sizeA) where sizeA is a vector of size n or 2-dimensional matrix [m,n].
How can I read the N-dimensioned matrix I described?

採用された回答

James Tursa
James Tursa 2013 年 2 月 13 日
編集済み: James Tursa 2013 年 2 月 13 日
Read the variable as a 1D using the total number of elements (e.g., 16*20*22*6*3*2) and then reshape the result. Since Fortran stores nD elements in memory in the same order that MATLAB does (column major) this will work. HOWEVER, unless you opened the file in Fortran as a stream, you will likely get record headers on the Fortran side that you will need to skip on the MATLAB side. Probably 4 bytes, but could be something else depending on the source machine and compiler used. E.g., something like this might work:
fid = fopen('yourfilename');
h = fread(fid,1,'*uint32'); % May need adjusting
a = fread(fid, 16*20*22*6*3*2, '*single');
b = fread(fid, 16*20*22*6*3*13, '*single');
c = fread(fid, 16*20*22*6*3*13, '*single');
a = reshape(a,[16 20 22 6 3 2]);
b = reshape(b,[16 20 22 6 3 13]);
c = reshape(c,[16 20 22 6 3 13]);
  3 件のコメント
James Tursa
James Tursa 2013 年 2 月 13 日
編集済み: James Tursa 2013 年 2 月 13 日
Your open statement is not stream, it is simply a sequential unformatted file. Thus I would expect to see the record header as I indicated. Since this header is machine and compiler specific (not part of the Fortran Standard) there is no guaranteed way to know for an arbitrary file what (if anything) is there. The only thing to do in a general sense is trial-and-error until you discover what works. But installations I have used have 4 bytes up front (e.g., Intel Fortran on a PC) so I would start with that as a first guess. Give my code a shot and see if it works.
Jim
Jim 2013 年 2 月 14 日
It looks like what you specified works. Thanks for the help!

サインインしてコメントする。

その他の回答 (1 件)

Aniruddh Murali
Aniruddh Murali 2018 年 9 月 27 日
If I am opening a bin in Fortran using the following command
open(unit=1,file='24092018.bin',
1 form='unformatted',status="old",access='sequential')
is there a way to open the same file in Matlab?

カテゴリ

Help Center および File ExchangeFortran with MATLAB についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by