Writing multiple matrices into text file
Show older comments
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?
Accepted Answer
More Answers (0)
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!