Printing heading to text file using fprintf

Hi, I am amending my text file with headings using the function fprintf. I took inspiration from other forums and made this script
load D
age=1:8;
year=1990:1:1997;
D_w_hdg=[year' age' D];
save('D.txt','D','-ascii')
fileID = fopen('D.txt','w');
fprintf(fileID,'%4s %3s %4s %4s %4s\n','year', 'age', 'male', 'male', 'male');
fprintf(fileID,'%4u %2u %2.6d %2.6d %2.6d\n',D_w_hdg);
fclose(fileID);
type 'D.txt'
The result in the Command window looks ok, but when I open the D.txt in Notepad the result is all in one line. I want the result in Notepad to reflect what is shown with the command type 'D.txt'. Is this possible?

 Accepted Answer

I do not have ‘D’, so I cannot run your code.
Try transposing your matrix:
fprintf(fileID,'%4u %2u %2.6d %2.6d %2.6d\n',D_w_hdg');

4 Comments

Unfortunately the results are the same with transpose. I have uploaded 'D.mat' to this questions, does it not show?
My code with the transpose works for me.
I copied this from Notepad:
year age male male male
1990 1 000255 000202 000177
1991 2 000016 000027 000019
1992 3 000016 000009 000006
1993 4 000004 000008 000010
1994 5 000010 000010 000013
1995 6 000006 000008 000019
1996 7 000003 000014 000009
1997 8 000006 000007 000008
I see I was opening it in notes before. Opening it in Notepad++ shows the desired results. Strange, but it works now. Thanks!
My pleasure!
Did you see the solution to your earlier Question that I posted?

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!