Writing Header for csv overwrites data in csv

3 visualizaciones (últimos 30 días)
MiauMiau
MiauMiau el 27 de Nov. de 2016
Respondida: Walter Roberson el 27 de Nov. de 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);

Respuesta aceptada

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

Más respuestas (1)

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

Iniciar sesión para comentar.

Categorías

Más información sobre Low-Level File I/O en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by