Clear Filters
Clear Filters

Having issues writing matrix to a binary file.

3 views (last 30 days)
Rikin
Rikin on 19 Apr 2024
Edited: James Tursa on 19 Apr 2024
For example,
A = [ 0.1712 0.2769 0.8235
0.7060 0.0462 0.6948
0.0318 0.0971 0.3171]
file1 = 'mat1.dat'
fileID = fopen(file1, 'w');
fwrite(fileID, size(data1), 'int32');
fwrite(fileID, data1, 'double')
fclose("all")
Using this code, the matrix size remains the same, but when I read it, the last row gets messed up, for example, see the output below:
0.0000 0.0318 0.0971
0.1712 0.2769 0.8235
0.7060 0.0462 0.6948
>> Anyone knows how to fix this?

Answers (2)

Voss
Voss on 19 Apr 2024
Edited: Voss on 19 Apr 2024
I suspect there's something wrong with how you are reading the file.
Here's an example of writing (using your code) and then reading a binary file, which reproduces the original matrix properly.
A = [ 0.1712 0.2769 0.8235
0.7060 0.0462 0.6948
0.0318 0.0971 0.3171]
A = 3x3
0.1712 0.2769 0.8235 0.7060 0.0462 0.6948 0.0318 0.0971 0.3171
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
size(A)
ans = 1x2
3 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
% writing
file1 = 'mat1.dat';
fileID = fopen(file1, 'w');
fwrite(fileID, size(A), 'int32');
fwrite(fileID, A, 'double');
fclose(fileID);
% reading
fileID = fopen(file1,'r');
sizA = fread(fileID,[1 2],'int32');
A_read = fread(fileID,sizA,'double');
fclose(fileID);
sizA
sizA = 1x2
3 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
A_read
A_read = 3x3
0.1712 0.2769 0.8235 0.7060 0.0462 0.6948 0.0318 0.0971 0.3171
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
isequal(A,A_read)
ans = logical
1

James Tursa
James Tursa on 19 Apr 2024
Edited: James Tursa on 19 Apr 2024
@Rikin You forgot to read in the sizes. You only read in the double data. The two int32 variables at the front obviously were packed together in the double read to produce the first double you read in (likely a very small denormal number), resulting in the rest of the data being shifted by one element. Voss posted your fix, which reads in the size data. E.g., this is probably what you ended up reading into that first double:
typecast(int32([3 3]),'double')
ans = 6.3660e-314
which printed as a 0.0000 in your output.

Community Treasure Hunt

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

Start Hunting!