Having issues writing matrix to a binary file.
7 次查看(过去 30 天)
显示 更早的评论
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?
回答(2 个)
Voss
2024-4-19
编辑:Voss
2024-4-19
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 个评论
James Tursa
2024-4-19
编辑:James Tursa
2024-4-19
@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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!