Csvwrite a matrix with header
23 次查看(过去 30 天)
显示 更早的评论
Hi,
I have a huge matrix (3000x3000) and I can write to a csv file with csvwrite('filename', cMatrix); But I also have a header defined in cellarray of strings as 'cHeader'. How should I save the matrix with header? In addition, I would also like to transpose the cHeader array to be the first column of the matrix. Is that possible?
Thanks,
Jennifer
1 个评论
jgg
2015-12-11
编辑:jgg
2015-12-11
Is it absolutely necessary that you export directly to a .csv? The issue is that it's actually a lot easier to write data to an .xls file instead when it is mixed. You can then use the .xls file to save it as a .csv instead. ( http://www.mathworks.com/help/matlab/ref/xlswrite.html )
The way to do this for a .csv is cumbersome, because you have to use low level export functions directly. See here: http://www.mathworks.com/help/matlab/import_export/write-to-delimited-data-files.html#br2ypq2-1 for a tutorial.
Note in either case you want to cast your data to a cell, which should not pose a problem (just use mat2cell); it will also let you add your column vector of labels at that point.
回答(2 个)
Joseph Cheng
2015-12-11
simple way is to write the header in using fprintf
cHeader = {'ab' 'bcd' 'cdef' 'dav'}; %dummy header
commaHeader = [cHeader;repmat({','},1,numel(cHeader))]; %insert commaas
commaHeader = commaHeader(:)';
textHeader = cell2mat(commaHeader); %cHeader in text with commas
%write header to file
fid = fopen('yourfile.csv','w');
fprintf(fid,'%s\n',textHeader)
fclose(fid)
%write data to end of file
dlmwrite('yourfile.csv',yourdata,'-append');
3 个评论
Ugur Keskin
2017-3-27
One comment on this solution: the textHeader is also including a comma at the end of the textHeader. This is not desired since the row of a CSV should not end with a comma.
I think the easiest fix is to add the following:
TextHeader = TextHeader(1:end-1);
This will remove the last comma.
Guillaume
2017-3-27
Or since R2013a, get rid of most of the lines building the header and simply:
textHeader = strjoin(cHeader, ',');
which will not put an extra comma
Bhavin Gajjar
2018-1-6
编辑:Bhavin Gajjar
2018-1-6
% Below code use the same logic described in above solution and it works fine. % This code shows the random data matrix of size 10x10 has appended in MyData.csv file with % heading of feature number and label
d = rand(10)
for i = 1:size(d,2) if i == 1 header1{i} = ['Label' num2str(i-1)] else
header1{i} = ['feature_' num2str(i-1)]; end end
header = strjoin(header1, ',');
fid = fopen('MyData.csv','w'); fprintf(fid,'%s\n',header) fclose(fid)
dlmwrite('MyData.csv',d,'-append');
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!