【问题标题】:Writing a mixed matrix of integers and strings to .csv in Matlab在 Matlab 中将整数和字符串的混合矩阵写入 .csv
【发布时间】:2013-02-11 21:10:20
【问题描述】:

也许这个问题之前已经回答过,但我似乎找不到任何好的文档。所以我的问题如下:

假设我在 Matlab 中有两个长度相同的向量

x = [1;2;3];
and
y = ['A';'B';'C'];

基本上我想创建矩阵{x,y}(即3 行,2 列),然后将其写入.csv 文件。所以最后我希望看到一个 .csv 文件,如

1,A
2,B
3,C

这只是一个模拟示例,但实际上我有 75 列,每列都是字符串或数字列。任何建议都非常感谢!

【问题讨论】:

    标签: matlab csv


    【解决方案1】:

    【讨论】:

    • 我编辑了我的答案,只是为了方便。使用您认为最简单的解决方案。
    【解决方案2】:

    如果你把你的数据分类成合适的cell

     A = cell(3,2);
     A{1,1} = 1;
     A{2,1} = 2;
     A{3,1} = 3;
     A{1,2} = 'A';
     A{2,2} = 'B';
     A{3,2} = 'C';
    

    然后你可以调用这个函数:

    cell2csv(filename,A)
    
    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      相关资源
      最近更新 更多