How to append the contents of array cells to .csv files?
9 ビュー (過去 30 日間)
古いコメントを表示
Hello, I would like to export the values in the cells of an array into a .csv file, such that the contents of each cell array make up a single "value" in the .csv file. For example
data =
4 x 3 cell array
{'information'} {'labels'} {'odds and ends'}
{'more information'} {'more labels'} {'odds and ends"}
{'info'} {'a label'} {'odds and ends'}
{'data'} {'output'} {'abcd'}
If the file ('data.csv') already has data in it, how do I append the data so that I get the following:
information,labels,odds and ends
more information,more labels,odds and ends
info,a label,odds and ends
data,output,abcd
I have tried using dlmwrite('data.csv',data,'-append')
but this produces
i,n,f,o,r,m,a,t,i,o,n,l,a,b,e,l,s,o,d,d,,a,n,d,,e,n,d,s
m,o,r,e,,i,n,f,o,r,m,a...... and so on
I know I can use something like xlswrite, but the file is being opened and closed many times, with a lot of data (and using xlswrite seems to slow the process down).
Any suggestions? Thanks!
Robert
1 件のコメント
dpb
2019 年 3 月 7 日
You'll have to write with fprintf the content of the cell array dereferenced to the strings...there's a rudimentary example "Export Cell Array to Text File" link at the bottom of the doc page for fprintf that illustrates the basic idea; you'll have to add the comma delimiter to the format as it's space-delimited and you would be well served to add the double-quotes around the strings since you do seem to have embedded blanks that are problematical on import oftentimes.
採用された回答
Robert
2019 年 3 月 7 日
編集済み: Robert
2019 年 3 月 7 日
20 件のコメント
dpb
2019 年 3 月 8 日
My output was from the straight command window; the command window doesn't have any of the presentation of data in a spreadsheet-like format. I'm guessing (since I don't use them for precisely such reasons) that you were using the variable editor window or whatever it is that TMW calls it, not just typing at the command line.
That tool is what "tried to help" by showing the root content of the cell but that disguised/hid that the actual array element was a cell containing a cell containing a string, not a cell containing a string.
Sometimes trying to be clever and helpful is more troublesome than it is actual help.
その他の回答 (1 件)
Walter Roberson
2019 年 3 月 7 日
If you must use dlmwrite(), then use
strjoin(arrayfun(@(IDX) strjoin(data(IDX,:), ','), 1:size(data,1), 'uniform', 0), '\n')
and dlmwrite that with a delimiter of '' (empty). Another way of phrasing this is that you need to pre-format all of the output and write it as a single vector with empty delimiter.
... Which is to say that using dlmwrite() for this is not recommended. Just fopen() with 'a' or 'at' mode and write the data yourself.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Spreadsheets についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!