MATLAB: How to write a .txt file in this way

savetext file

Best Answer

Writing that file is easy and efficient with one loop:
C = {'pre','post','shift'};
[fid,msg] = fopen('test.txt','wt');
assert(fid>=3,msg)
for k = 1:numel(C)
D = rand(1,12); % fake data
X = 1:numel(D);
fprintf(fid,'"d0_L2_%s"\n',C{k})
fprintf(fid,'"M%d" %.16f\n',[X(:),D(:)].')
end
fclose(fid);
It generates this file:
"d0_L2_pre"
"M1" 0.8101833471970885
"M2" 0.3228280263956013
"M3" 0.9313125812216142
"M4" 0.0930197953819751
"M5" 0.1431754035600110
"M6" 0.0191395364706218
"M7" 0.3733887218661779
"M8" 0.5956394051737841
"M9" 0.1549615401190287
"M10" 0.2166245210274229
"M11" 0.1375581615241128
"M12" 0.4638896483775406
"d0_L2_post"
"M1" 0.9800029232465585
"M2" 0.6889261537441198
"M3" 0.3944793330174778
"M4" 0.9784100986414408
"M5" 0.7345622798805288
"M6" 0.9344731006203441
"M7" 0.5680906731481710
"M8" 0.3412121838601810
"M9" 0.2602806479751585
"M10" 0.5306524038227418
"M11" 0.3839486545914291
"M12" 0.6184793329342448
"d0_L2_shift"
"M1" 0.4395118376041331
"M2" 0.9157654018281208
"M3" 0.4117131471312308
"M4" 0.1698818550755265
"M5" 0.4333299487649594
"M6" 0.1036376088665931
"M7" 0.7037719110569336
"M8" 0.3658712106700369
"M9" 0.7182559095641131
"M10" 0.0579546739859127
"M11" 0.7510618251853217
"M12" 0.8921570052671490