Hello Everyone, I have a cell array C where the first row is string and the remaining rows contain numbers. How do I write the variable C into a CSV file?
For example,
c = {'abc' 'def' 'ghk';[23],[24],[67];[87],[13],[999];[656],[6767],[546]};
Thanks

 채택된 답변

Cedric
Cedric 2013년 4월 5일
편집: MathWorks Support Team 2018년 11월 27일

28 개 추천

To write the data in C to a CSV file. Use “writetable” in combination with the “cell2table” function.
% Convert cell to a table and use first row as variable names
T = cell2table(c(2:end,:),'VariableNames',c(1,:))
% Write the table to a CSV file
writetable(T,'myDataFile.csv')
For more information see:

댓글 수: 5

Or you could do the whole thing with fprintf
c = {'abc' 'def' 'ghk';[23],[24],[67];[87],[13],[999];[656],[6767],[546]};
fid = fopen('junk.csv','w')
fprintf(fid,'%s, %s, %s\n',c{1,:})
fprintf(fid,'%f, %f, %f\n',c{2:end,:})
fclose(fid)
Cedric
Cedric 2013년 4월 5일
Yes, you should propose this as a solution; I don't know why I was stuck thinking that the OP wanted a CSV/DLM-like function call somewhere, but your solution is certainly better.
Jalaj Bidwai
Jalaj Bidwai 2013년 4월 6일
Thanks guys..for replying and giving the solution..Thankyou very much
Image Analyst
Image Analyst 2015년 10월 19일
Sara Khalifa's flag moved here:
Great Solution. Thanks!
Bidisha Das
Bidisha Das 2018년 8월 29일
What if I want the csv file in append mode?

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

추가 답변 (8개)

Jon
Jon 2013년 4월 5일

4 개 추천

You could do it as follows with fprintf
c = {'abc' 'def' 'ghk';[23],[24],[67];[87],[13],[999];[656],[6767],[546]};
fid = fopen('junk.csv','w')
fprintf(fid,'%s, %s, %s\n',c{1,:})
fprintf(fid,'%f, %f, %f\n',c{2:end,:})
fclose(fid)

댓글 수: 6

Cedric
Cedric 2013년 4월 5일
+1 ;-)
Jalaj Bidwai
Jalaj Bidwai 2013년 4월 6일
The solution is legitimate to this particular problem.But what if I have many column instead of just 3(as is the case here).I just composed the problem to from a large chunk of data that I have...THe actual data has 30 columns.In the present solution I suppose that each %s in the first fprintf is for each of the heading string(i.e abc def ghk).
You could generalize it for an arbitrary number of columns as follows:
c = {'abc' 'def' 'ghk';[23],[24],[67];[87],[13],[999];[656],[6767],[546]};
fid = fopen('junk.csv','w')
numColumns = size(c,2);
% use repmat to construct repeating formats
% ( numColumns-1 because no comma on last one)
headerFmt = repmat('%s,',1,numColumns-1);
numFmt = repmat('%f,',1,numColumns-1);
fprintf(fid,[headerFmt,'%s\n'],c{1,:})
fprintf(fid,[numFmt,'%f\n'],c{2:end,:})
fclose(fid)
Even better, if you have the statistics toolbox, you can use a dataset array and do the whole thing very cleanly as:
ds = cell2dataset(c);
export(ds,'file','junk2.csv','delimiter',',')
Cedric
Cedric 2013년 4월 8일
I don't know if the OP will read your comment, but thank you for the information; I didn't know EXPORT.
Jalaj Bidwai
Jalaj Bidwai 2013년 4월 8일
Jonathan,Fanstastic. Both of the ways have worked for me..Thank you for the help..I really aprreciate it...
Jonathan, Perfect! Thanks so much for your input.

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

Azzi Abdelmalek
Azzi Abdelmalek 2013년 4월 5일
편집: Azzi Abdelmalek 2013년 4월 5일

1 개 추천

use csvwrite functionn

댓글 수: 2

Jon
Jon 2013년 4월 5일
csvwrite only works on numeric arrays, not cell arrays with strings and numbers
Youcef Yahiaoui
Youcef Yahiaoui 2015년 9월 19일
Azzi,good to see your comments here. I usually use fprintf(fid...) for the first header lines then use csvwrite with the option -append...

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

Zumbo_123
Zumbo_123 2016년 1월 7일

0 개 추천

Alternatively, you could use the method developed by Sylvain Fiedler. Below is the link to the file. It works with empty cells, numeric, char, string and logical cells. One array can contain all of them, but only one value per cell.
Peter Farkas
Peter Farkas 2017년 10월 9일

0 개 추천

Convert to table and use writetable function T = cell2table(c(2:end, :)); T.Properties.VariableNames = c(1:end, :); writetable(T, res.csv);
Aaron Thrasher
Aaron Thrasher 2018년 4월 20일

0 개 추천

I came to this page looking for an answer and found that all solutions were very slow for large arrays that include numeric and char based cell arrays of non-standard combinations. Instead, I created my own based off of previous comments and other research. I hope this helps someone as it has helped me reduce the time significantly.

function cellWrite(filename,origCell)
% save a new version of the cell for reference
modCell = origCell;
% assume some cells are numeric, in which case set to char
iNum = cellfun(@isnumeric,origCell);
%% Method 1 using indexing and straight conversion = 7 sec
tic
modCell(iNum) = cellstr(num2str([origCell{iNum}]'));
% toc
%% Method 2 using arrayfun = 25 sec
% tic
% modCell(iNum) = arrayfun(@num2str,[origCell{iNum}],'unif',0);
% toc
% tic
[rNum,cNum] = size(origCell);
frmt = repmat([repmat('%s,',1,cNum-1),'%s\n'],1,rNum);
fid = fopen(filename,'w');
fprintf(fid,frmt,modCell{:});
fclose(fid);
toc
end

댓글 수: 2

Aaron Thrasher
Aaron Thrasher 2018년 4월 20일
Correction to the code - the cell needs to be transposed before writing because the data is written left to right vs. matlab reading cell top down.
Michael Barrow
Michael Barrow 2019년 10월 19일
Thanks for sharing your work!

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

Yoram Segal
Yoram Segal 2018년 8월 27일

0 개 추천

convert the cell to a table and save the table as CSV
TT = array2table(C,'VariableNames',{'abc' 'def' 'ghk'});
writetable(TT,filename);
To read it back you can use TT = readtable(filename)
TripleSSSS
TripleSSSS 2019년 4월 4일

0 개 추천

Matlab now support write from cell array to file
please check: writecell

카테고리

도움말 센터File Exchange에서 Text Data Preparation에 대해 자세히 알아보기

질문:

2013년 4월 5일

답변:

2021년 6월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by