Formatting the output statement.

2 vues (au cours des 30 derniers jours)
Mohana
Mohana le 14 Jan 2015
Commenté : Guillaume le 19 Jan 2015
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.
  2 commentaires
Sara
Sara le 14 Jan 2015
What are V1_2006; V2_2006; V3_2006; V4_2006?
If you want one column, you'll have to replace \t with \n in the last line.
Mohana
Mohana le 19 Jan 2015
V1_2006; V2_2006; V3_2006; V4_2006 are four different variables for the year 2006 (daily)

Connectez-vous pour commenter.

Réponse acceptée

Guillaume
Guillaume le 19 Jan 2015
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.
  2 commentaires
Mohana
Mohana le 19 Jan 2015
Thanks so there is a difference in using ; and ,. Regards. Mohan.
Guillaume
Guillaume le 19 Jan 2015
There is a major difference between the two. , is horizontal concatenation, ; is vertical concatenation.

Connectez-vous pour commenter.

Plus de réponses (0)

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by