Having issues writing matrix to a binary file.
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
Réponses (2)
Voss
le 19 Avr 2024
Modifié(e) : Voss
le 19 Avr 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 commentaires
James Tursa
le 19 Avr 2024
Modifié(e) : James Tursa
le 19 Avr 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 commentaires
Voir également
Catégories
En savoir plus sur Text Files dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!