Having issues writing matrix to a binary file.

조회 수: 7 (최근 30일)
Rikin
Rikin 2024년 4월 19일
편집: James Tursa 2024년 4월 19일
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
Voss
Voss 2024년 4월 19일
Please share the code you use to read the file as well.

댓글을 달려면 로그인하십시오.

답변 (2개)

Voss
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]
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 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')
ans = 6.3660e-314
which printed as a 0.0000 in your output.

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by