Writing Header for csv overwrites data in csv

조회 수: 2 (최근 30일)
MiauMiau
MiauMiau 2016년 11월 27일
답변: Walter Roberson 2016년 11월 27일
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);

채택된 답변

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

추가 답변 (1개)

Image Analyst
Image Analyst 2016년 11월 27일
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
MiauMiau
MiauMiau 2016년 11월 27일
? Thats what I do..?
Image Analyst
Image Analyst 2016년 11월 27일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by