Writing Header for csv overwrites data in csv

3 views (last 30 days)
Hi!
I have a 138x2 matrix A, which I save as a csv:
csvwrite('A.csv',A);
Now I want to add for each column a header, the csv at the end should have a 139x2 format. The first header is called "PIN", the second "Pred". However when I use the following code, all my data from above is overwritten, and only the headers are left! What am I doing wrong?
cHeader = {'Pin' 'Pred'}; %dummy header
commaHeader = [cHeader;repmat({','},1,numel(cHeader))]; %insert commaas
commaHeader = commaHeader(:)';
textHeader = cell2mat(commaHeader);
fid = fopen('A.csv','w');
fprintf(fid,'%s\n',textHeader);
fclose(fid);

Accepted Answer

Walter Roberson
Walter Roberson on 27 Nov 2016
fid = fopen('A.csv', 'wt');
fprintf(fid, '%s,%s\n', 'Pin', 'Pred');
fprintf(fid, '%g,%g\n', A.'); %transpose is important!
fclose(fid);

More Answers (1)

Image Analyst
Image Analyst on 27 Nov 2016
I don't think csvwrite() handles strings and numbers. After you write out the numbers with csvwrite(), then use fopen(), fgetl(), fprintf(), and fclose() to insert the string(s) at the beginning of the file.
  2 Comments
Image Analyst
Image Analyst on 27 Nov 2016
That's why I wrote it. Because that's what I'd do and I suggest that's what you should do also. See the loop in the example for fgetl(). First write out your lines, then transfer all the other stuff to a temporary file. Then delete your original .csv file and use movefile() to rename your temporary file.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!