Csvwrite a matrix with header

63 views (last 30 days)
JFz
JFz on 11 Dec 2015
Edited: Bhavin Gajjar on 6 Jan 2018
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 Comment
jgg
jgg on 11 Dec 2015
Edited: jgg on 11 Dec 2015
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.

Sign in to comment.

Answers (2)

Joseph Cheng
Joseph Cheng on 11 Dec 2015
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 Comments
Ugur Keskin
Ugur Keskin on 27 Mar 2017
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
Guillaume on 27 Mar 2017
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

Sign in to comment.


Bhavin Gajjar
Bhavin Gajjar on 6 Jan 2018
Edited: Bhavin Gajjar on 6 Jan 2018
% 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');

Tags

Products

Community Treasure Hunt

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

Start Hunting!