MATLAB: Generating an array from binary data

binaryfread

Hi,
I'm having a little trouble generating an array from a binary file.
The data is contained in the attached file.
I'm using the snippet of code below to read the data.
path = 'd_300x300-Oxs_TimeDriver-Magnetization-000000026-0000105.txt';
A = fopen(path);
fseek(A,987,'bof');
B = fread(A,[160,20],'8*uint8=>uint8',16,'b');
C = typecast(B(:,1),'double');
dlmwrite('output.txt',C);
The data shows the pixel value element-by-element, for a 20×20-pixel array. So, I'm trying to read the data directly in to its pixel location ie. put the first 20 values in to a column, then the next 20 values in to the next column, and so on.
When I inspect the text format here from output.txt, the data comes out perfectly well in column format. The first data point is indeed 8.3524e5. However, when I scan across the row, the readout is incorrect (the first value should again be 8.3524e5).
I believe that the error is coming about because Matlab is not recognizing that one element is comprised of 8 bits. It recognizes that 8 bits == 1 column, but it does not read 8 bits == 1 element, hence the required [160,20] output size.
Does anyone know how to fix this?
Thanks very much in advance,
Carl

Best Answer

  • For every 8 bytes of data that the code reads in, 16 bytes are then skipped. As Carl has already answered, this is intentional due to the data corresponding to the x/y/z components of magnetization of a material, and the skipping is needed to look at just one component.
    I ran your code and obtained the same results: the first element of the first column was 835237.585310508, and the first element of the second column was something else (837157.626801806).
    I tried something different by replacing the
    B = fread(A,[160,20],'8*uint8=>uint8',16,'b');
    C = typecast(B(:,1),'double');
    with
    B = fread(fid,[20,20],'1*double',16);
    For every double read, we skip two. This line of code returned the same results as the reading in of 8 unsigned integers and the use of typecast.
    What I did notice about B is that the last column is identical to the first but in reverse order, the second last column is identical to the second but in reverse order. In fact they all were near-identical if I ran the following
    for k=1:10
    if max(abs(B(:,k) - flipud(B(:,20-k+1))))<0.00000001
    fprintf('near-identical for %d!\n',k);
    end
    end
    Again, as Carl has already answered, this behaviour is expected as the system is simple and highly symmetric.