将单元格(matlab)写入CSV文件

时间:2013-01-27 19:14:59

标签: matlab csv 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'

到csv文件?

我试过

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

但它会显示以下错误消息:

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

1 个答案:

答案 0 :(得分:12)

我刚刚试过这个,但它确实有效:

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

cell2csv作为

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);

我复制了代码,因为我不知道MathWorks File Exchange上的函数是否可用。但Google也应该提供帮助。