Read binary matrix from a file in Matlab

2019-09-17 20:41发布

问题:

I have a binary square matrix with complex values, stored in a .bin format file. I have tried to read this 100-by-100 matrix with a Matlab script:

i=fopen('matrix.bin','r')
A=fread(i,[100 100]

This code does not correctly read the complex values contained in A. I only get a 100-by-100 matrix of integers.

回答1:

MATLAB fread support ANSI C types, but there is no native ANSI C types that represent complex numbers. Most likely, a complex number is stored as a pair of real and imaginary numbers.

Without information as to how the binary file is saved, you can still perform some test to figure this out. If the complex number is represented as a real part and an imaginary part, and both in double precision, then a single complex number would take up 8 + 8 = 16 bytes. We can test this by navigating to the end of the file, and see how many bytes there are.

fID = fopen('matrix.bin','r')
fseek(fID, 0, 'eof')      % Go to the end of file
ftell(fID)                % Tell current position in the open file
fclose(fID)

If this number is equal to 16 * 100 * 100 = 160000, then you're in luck. There is no extra stuff saved in this file, and you can simply read the data by this code:

fID = fopen('matrix.bin','r')
data = []
for ii = 1:10000
    data = [data; fread(fID, 2, 'double')']
end
fclose(fID)

You'll end up with a 10000*2 array, with each row representing a complex number. If the file size is 80000, then both real and imaginary part could be saved in single data type. If file size is some other number, then it probably means some additional information is stored in the binary. You'll have to know what additional information is stored so you can read the file correctly.