Writing Header for csv overwrites data in csv
2 次查看(过去 30 天)
显示 更早的评论
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);
0 个评论
采纳的回答
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);
0 个评论
更多回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!