How can I append matrix in loop?

1 view (last 30 days)
I made the code below
fileid = fopen('test.txt' , 'w');
a = rand(2,2,2);
fileid = fopen('test.txt' , 'w');
for i = 1:2
fprintf(fileid,num2str(i));
fprintf(fileid,'\n');
dlmwrite('test.txt',a(:,:,i),'-append','delimiter',' ');
end
So the result like that
1
2
95751 0.15761
0.96489 0.97059
0.95717 0.80028
0.48538 0.14189
I want a append immediately after i like that
1
95751 0.15761
0.96489 0.97059
2
0.95717 0.80028
0.48538 0.14189
Any one can help me solve this problem?
Thanks

Accepted Answer

Walter Roberson
Walter Roberson on 21 Aug 2016
a = rand(2,2,2);
for i = 1:2
fileid = fopen('test.txt' , 'a');
fprintf(fileid,num2str(i));
fprintf(fileid,'\n');
fclose(fileid);
dlmwrite('test.txt',a(:,:,i),'-append','delimiter',' ');
end
The dlmwrite() will not happen properly if you have the file open for writing.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!