writetable 在 Matlab 中用空白替换 NaN

writetable replace NaN with blanks in Matlab

给定一个包含许多 NaN 的 Matlab table,我如何将这个 table 写成 excel 或 NaN 被空格替换的 csv 文件?

我使用以下函数:

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

writetable(T, filename)

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

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

您只需要 xlswrite for that. It replaces NaNs with blanks itself. Use table2cell or the combination of table2array and num2cell 先将 table 转换为元胞数组。使用 table 的 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  

产量:


虽然我认为上面的解决方案更简单但是如果你真的想使用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

老实说,我认为以您描述的格式输出数据的最直接方法是使用 xlswrite as . However, if you really want to use writetable, the only option I can think of is to encapsulate every value in the table in a cell array 并将 nan 条目替换为空单元格。从这个示例 table 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

这就是 table 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');