【问题标题】:MATLAB writing csv with mixed alphanumeric strings, scalar arrays, nansMATLAB 使用混合字母数字字符串、标量数组、nans 编写 csv
【发布时间】:2017-05-10 02:52:06
【问题描述】:

好的,来自 Python 并且之前从未使用过 MATLAB,使用 MATLAB 将数据写入 csv 似乎是不必要的困难......

所以我的数据看起来像这样:

col1       A2A    B2   CC3     D5
asd189     123    33   71119   18291
as33d      1311   31   NaN     1011
asd189     NaN    44   79      191

它有 N 个由字母数字字符串组成的标题列。 它有一个长度为 M 的最左边的列,由字母数字字符串组成。 它有一个 (M-1) x (N-1) NUMERIC 数据数组,可能包含 NaN。

您能否提供将其写入 csv 的代码?我无法使用 xlswrite 函数,因为我在没有安装 Excel 的集群上。真的只是想继续进行实际的数据分析。谢谢

【问题讨论】:

    标签: matlab csv export-to-csv


    【解决方案1】:

    您只能使用csvwrite 直接编写矩阵(而不是元胞数组),并且正如您所说,您需要为xlswrite 安装 Excel,这样您就可以进行低级操作。您可以查看写入文本文件 here 的演练,以及以下示例代码:

    % Initialise example cell array
    M = {'col1',  'A2A', 'B2', 'CC3',  'D5'
         'asd189', 123,  33,    71119, 18291
         'as33d',  1311, 31,    NaN,   1011
         'asd189', NaN,  44,    79,    191};
    % Open a file for writing to (doesn't have to already exist, can specify full directory)
    fID = fopen('test.csv','w');
    % Write header line, formatted as strings with comma delimiter. Note \r\n for new line
    fprintf(fID, [repmat('%s, ', 1, size(M,2)-1),'%s\r\n'], M{1,:});
    % Loop through other rows
    for row = 2:size(M,1)
        % Write each line of cell array, with first column formatted as string 
        % and other columns formatted as floats
        fprintf(fID, ['%s, ', repmat('%f, ', 1, size(M,2)-2),'%f\r\n'], M{row,:});
    end
    % Close file after writing
    fclose(fID);
    

    结果:

    【讨论】:

      【解决方案2】:

      使用writetable。与使用csvwritexlswritefprintf 等低级命令相比,它使写入CSV(或Excel 文件或其他以文本分隔的文件格式)更容易。

      >> t = table({'asd189';'as33d';'asd189'},[123;1311;NaN],[33;31;44],[71119;NaN;79],[18291;1011;191]);
      >> t.Properties.VariableNames = {'col1','A2A','B2','CC3','D5'}
      t = 
            col1      A2A     B2     CC3      D5  
          ________    ____    __    _____    _____
          'asd189'     123    33    71119    18291
          'as33d'     1311    31      NaN     1011
          'asd189'     NaN    44       79      191
      >> writetable(t,'myfile.csv')
      

      如果您的数据当前未存储为表格(可能存储在数组或元胞数组中),则可以使用array2tablecell2table 等实用函数轻松转换为表格。您只需为此付出一点时间惩罚。

      PS - 您无需安装 Excel 即可写入 Excel 文件。之后您可能无法读取它们,但 MATLAB 仍然可以编写它们。但听起来你还是更喜欢 .csv。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-04
        • 2020-04-27
        相关资源
        最近更新 更多