Having issues writing matrix to a binary file.
7 views (last 30 days)
Show older comments
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?
1 Comment
Answers (2)
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]
size(A)
% 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
A_read
isequal(A,A_read)
0 Comments
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')
which printed as a 0.0000 in your output.
0 Comments
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!