问题描述
给定一个包含许多NaN
的Matlab表,如何将该表编写为excel或csv文件,其中NaN替换为空格?
Given a Matlab table that contains many NaN
, how can I write this table as an excel or csv files where the NaN are replaced by blanks?
我使用以下功能:
T = table(NaN(5,2),'VariableNames',{'A','C'})
writetable(T, filename)
我不想将其替换为零.我想要输出文件:
- NaN和 均为空白
- 变量名称包含在输出中.
推荐答案
您只需要 xlswrite
.它用空格本身替换NaN
.使用 table2cell
或 table2array
和 num2cell
首先将表格转换为单元格数组.使用表的VariableNames
属性检索变量名称,并用单元格数组填充它们.
You just need xlswrite
for that. It replaces NaN
s with blanks itself. Use table2cell
or the combination of table2array
and num2cell
to convert your table to a cell array first. Use the VariableNames
property of the table to retrieve the variable names and pad them with the cell array.
data= [T.Properties.VariableNames; table2cell(T)];
%or data= [T.Properties.VariableNames; num2cell(table2array(T))];
xlswrite('output',data);
样品运行:
Sample run for:
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
然后:
Although the above solution is simpler in my opinion but if you really want to use writetable
then:
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
这篇关于writetable在Matlab中用空格替换NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!