MATLAB: Formatting the output statement.

data formatingMATLAB

I have written a code to insert date in a column along with other variables (V1, V2, V3,…)
%Date
start={'01.01.2006'};
start1={'02.01.2006'};
stop={'31.12.2006'};
new_start=datenum(start,'dd.mm.yyyy');
new_start1=datenum(start1,'dd.mm.yyyy');
new_stop=datenum(stop,'dd.mm.yyyy');
difference=new_start1-new_start;
out=new_start:difference:new_stop;
D_06=datestr(out,'dd-mm-yyyy');
D_2006=datenum(D_06,'dd-mm-yyyy');
[Y2006]=D_2006;
I have written a code to write the ouput in a file as follows:
fid = fopen('Sample1.xls','w');
fprintf(fid,'Date \t V1 \t V2 \t V3 \t V4\n');
%fprintf(fid,'2006\n');
V2006=[Y2006; V1_2006; V2_2006; V3_2006; V4_2006];
fprintf(fid,'%d \t %f \t %f \t %f \t %f \n',V2006);
But the date is being written in 5 columns instead of one colum, what is the problem with the output format statement. Kindly help. Thanks in advance. Regards. Mohan.

Best Answer

This is probably what you wanted to write:
fid = fopen('Sample1.xls','wt'); %Use 'wt' for text files. Why is the extension xls when it's a text file?
fprintf(fid,'Date \t V1 \t V2 \t V3 \t V4\n');
V2006 = [Y2006, V1_2006, V2_2006, V3_2006, V4_2006]; %note: HORIZONTAL concatenation instead of vertical
fprintf(fid,'%d \t %f \t %f \t %f \t %f \n',V2006);
fclose(fid);
However, a much simpler way is to use writetable:
V2006 = [Y2006, V1_2006, V2_2006, V3_2006, V4_2006];
t = array2table(V2006, 'VariableNames', {'Date', 'V1', 'V2', 'V3', 'V4'});
writetable(t, 'Sample1.txt', 'Delimiter', '\t'); %If you give it an xls extension, it'll write an Excel file.