Advice on reading an unformatted Fortran binary file into Matlab
4 views (last 30 days)
Show older comments
Hi,
I have used Fortran 90 to generate a huge array of reals (the dimensions are 5001 by 2287), and I have written this array to an unformatted Fortran binary using Fortran commands like the following:
OPEN(UNIT=15, FILE="output.dat", STATUS="REPLACE", ACTION="WRITE", FORM="UNFORMATTED")
WRITE(15) data
CLOSE(UNIT=15)
Do you have any experience in reading unformatted Fortran binary files into Matlab? When I search around for options, it seems that there are several. For example, it seems that some people recommend first dumping the binary to a hexadecimal file, and then read the hexadecimal file using a Matlab script. (Unfortunately, I do not immediately know how to dump a Fortran binary to hexadecimal since I am new to Fortran. I will have to figure this out first.) On the other hand, it seems that there is a (non-MathWorks produced, non-MathWorks supported?) matOpen/matPutVariable API. However, it seems that this is mainly for C/C++, and might require some work to communicate with Fortran.
Do you have any advice of which direction I should head? Or would it be better if I somehow converted the Fortran binary to an ASCII text file and then read that text file into Matlab using dlmread?
Thank you very much for your time.
Andrew DeYoung
Carnegie Mellon University
0 Comments
Accepted Answer
James Tursa
on 28 Jul 2011
Fortran unformatted binary, unfortunately, is not like C binary or MATLAB binary. Fortran binary typcially puts in record markers mixed in along with the actual data. You can read this file directly into MATLAB with simple fopen and fread commands, but you will be faced with weeding out the record markers. I don't suppose you know what the record markers are or how long each record is do you? If not, I would advise reading in a small chunk (maybe 100-200 bytes worth) and try to figure out how many bytes up front are used for this (I would expect maybe 4 or 8) and how many bytes are used inbetween records as well. How good are you at hex sleuthing? (Too bad you didn't write this out using Fortran stream instead of Fortran unformatted binary)
3 Comments
James Tursa
on 29 Jul 2011
If you can re-run your program to generate the file, and your compiler supports stream, then by all means try that route. Reading it directly into MATLAB should be very easy. Another possibility is writing a Fortran mex routine to read the variable in and return it to MATLAB.
More Answers (0)
See Also
Categories
Find more on Fortran with MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!