How to read an N-dimensioned matrix from a binary file
37 views (last 30 days)
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)
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 on 13 Feb 2013
Edited: James Tursa on 13 Feb 2013
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]);
More Answers (1)
Aniruddh Murali on 27 Sep 2018
If I am opening a bin in Fortran using the following command
is there a way to open the same file in Matlab?