可写的在Matlab中用空格替换NaN

时间:2017-08-18 09:51:14

标签: excel matlab matlab-table

给定一个包含许多NaN的Matlab表,如何将此表写为excel或csv文件,其中NaN被空格替换?

我使用以下功能:

T = table(NaN(5,2),'VariableNames',{'A','C'})

writetable(T, filename)

我不想用零替换它。我想要输出文件:

  1. 对NaN和
  2. 有空白
  3. 变量名称包含在输出中。

2 个答案:

答案 0 :(得分:5)

你需要xlswrite。它用空白替换NaN s。使用table2celltable2arraynum2cell的组合将表格转换为单元格数组。使用表的VariableNames属性检索变量名称并使用单元格数组填充它们。

data= [T.Properties.VariableNames; table2cell(T)];
%or data= [T.Properties.VariableNames; num2cell(table2array(T))];
xlswrite('output',data);

示例运行:

T = table([1;2;3],[NaN; 410; 6],[31; NaN; 27],'VariableNames',{'One' 'Two' 'Three'})

T =

  3×3 table

    One    Two    Three
    ___    ___    _____

    1      NaN     31  
    2      410    NaN  
    3        6     27  

的产率:

output

虽然上面的解决方案在我看来比较简单但是如果你真的想使用writetable那么:

tmp = table2cell(T);             %Converting the table to a cell array
tmp(isnan(T.Variables)) = {[]};  %Replacing the NaN entries with []
T = array2table(tmp,'VariableNames',T.Properties.VariableNames); %Converting back to table
writetable(T,'output.csv');      %Writing to a csv file

答案 1 :(得分:2)

老实说,我认为以您描述的格式输出数据的最直接方式是使用xlswrite作为Sardar did in his answer。但是,如果确实想要使用writetable,我能想到的唯一选择是将表中的每个值封装在cell array中并替换nan带有空单元格的条目。从此示例表T开始,包含随机数据和nan值:

T = table(rand(5,1), [nan; rand(3,1); nan], 'VariableNames', {'A', 'C'});

T = 
            A                    C        
    _________________    _________________

    0.337719409821377                  NaN
    0.900053846417662    0.389738836961253
    0.369246781120215    0.241691285913833
    0.111202755293787    0.403912145588115
    0.780252068321138                  NaN

以下是进行转换的一般方法:

for name = T.Properties.VariableNames  % Loop over variable names
  temp = num2cell(T.(name{1}));        % Convert numeric array to cell array
  temp(cellfun(@isnan, temp)) = {[]};  % Set cells with NaN to empty
  T.(name{1}) = temp;                  % Place back into table
end

这就是表T最终看起来像:

T = 
             A                      C         
    ___________________    ___________________

    [0.337719409821377]    []                 
    [0.900053846417662]    [0.389738836961253]
    [0.369246781120215]    [0.241691285913833]
    [0.111202755293787]    [0.403912145588115]
    [0.780252068321138]    []

现在您可以将其输出到writetable的文件:

writetable(T, 'sample.csv');

enter image description here