Writing multiple matrices into text file
15 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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?
0 comentarios
Respuesta aceptada
dpb
el 13 de En. de 2019
Editada: dpb
el 13 de En. de 2019
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 comentarios
dpb
el 14 de En. de 2019
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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Text Files en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!