Writing Header for csv overwrites data in csv

2 vues (au cours des 30 derniers jours)
MiauMiau
MiauMiau le 27 Nov 2016
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);

Réponse acceptée

Walter Roberson
Walter Roberson le 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);

Plus de réponses (1)

Image Analyst
Image Analyst le 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 commentaires
MiauMiau
MiauMiau le 27 Nov 2016
? Thats what I do..?
Image Analyst
Image Analyst le 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.

Connectez-vous pour commenter.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by