MATLAB: How to append matrix in loop

appendloop

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

Best Answer

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.