Writing a cell (matlab) to a CSV file

血红的双手。 提交于 2019-11-29 09:46:15

问题


How can I save this cell

    data = cell([3 2]);
    data{1,1} = 'Bla';
    data{2,1} = 'Bla1';
    data{3,1} = 'Bla2';
    data{1,2} = '2';
    data{2,2} = '3';
    data{3,2} = '1'

to a csv file?

I tried

dlmwrite('C:\Users\Ro\Desktop\Mestrado\Resultados\Tabelas\VaR_tab.csv',data,'delimiter',';')

but it give this error message:

Error using dlmwrite (line 118)
The input cell array cannot be converted to a matrix.

回答1:


I just tried this, and it worked:

filename = 'test';
cell2csv(filename,data)

with cell2csv available as

function cell2csv(filename,cellArray,delimiter)
% Writes cell array content into a *.csv file.
% 
% CELL2CSV(filename,cellArray,delimiter)
%
% filename      = Name of the file to save. [ i.e. 'text.csv' ]
% cellarray    = Name of the Cell Array where the data is in
% delimiter = seperating sign, normally:',' (default)
%
% by Sylvain Fiedler, KA, 2004
% modified by Rob Kohr, Rutgers, 2005 - changed to english and fixed delimiter
if nargin<3
    delimiter = ',';
end

datei = fopen(filename,'w');
for z=1:size(cellArray,1)
    for s=1:size(cellArray,2)

        var = eval(['cellArray{z,s}']);

        if size(var,1) == 0
            var = '';
        end

        if isnumeric(var) == 1
            var = num2str(var);
        end

        fprintf(datei,var);

        if s ~= size(cellArray,2)
            fprintf(datei,[delimiter]);
        end
    end
    fprintf(datei,'\n');
end
fclose(datei);

I copied the code cause I am not aware if the function is any longer available on MathWorks File Exchange. But Google should help too.



来源:https://stackoverflow.com/questions/14551153/writing-a-cell-matlab-to-a-csv-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!