Writing multiple matrices into text file

조회 수: 15 (최근 30일)
jhz
jhz 2019년 1월 13일
댓글: jhz 2019년 1월 15일
I would like to write multiple matrices of different dimensions always changing in a loop into a text file one after another. I have to add a header line too. Here is a sample code what I am trying to do. This is not my project, however I have to do something similar.
But this code is giving me only last matrix (C) in the text file overwriting the first two.
I want output like this:
1
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
2
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
3
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
savepath=pwd;
A = magic(4);
B = magic(5);
C = magic(6);
MyData={A, B, C}';
filename = fullfile(savepath, 'myFile.txt');
for i=1:numel(MyData)
fid(i)=fopen(filename, 'wt');
fprintf(fid(i), '%d\n', i); % header
fclose(fid(i));
dlmwrite(filename,MyData{i},'delimiter','\t','-append', 'roffset', 1);
end
I don't know what I am doing wrong?

채택된 답변

dpb
dpb 2019년 1월 13일
편집: dpb 2019년 1월 13일
fid(i)=fopen(filename, 'wt');
From the doc for fopen --
permission: 'w' Open or create new file for writing. Discard existing contents, if any.
'a' Open or create new file for writing. Append data to the end of the file.
So, every subsequent loop kills the preceding content and creates a new file content.
NB: If you change existing code to use 'a' and rerun it, the new file will contain the new datasets PLUS that which was left from the last test run you made earlier. You'll have to write the code to control whether you're making a new file at the beginning or not, depending on what is wanted.
  댓글 수: 3
dpb
dpb 2019년 1월 14일
No problem...easy to overlook a detail! :)
You could, btw, use save filename.txt -ascii -tabs
to write the file if you were to just store the "header" data in a variable as well as the arrays and then write the whole file in a single call. save will use default precision on writing, however, so that if the real data are actually integer-valued as the example, there would be some extra zeros written that wouldn't be strictly necessary.
Could be worth investigating, however, if the actual arrays are large. Of course, then .mat files are far more efficient unless there really is a reason for text.
jhz
jhz 2019년 1월 15일
This is a good suggestion which I didn't know. I would consider it in my project. Thank you.

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

추가 답변 (0개)

카테고리

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