给定一个包含许多的 Matlab 表,NaN
我如何将此表写为 excel 或 csv 文件,其中 NaN 被空白替换?
我使用以下功能:
T = table(NaN(5,2),'VariableNames',{'A','C'})
writetable(T, filename)
我不想用 zeros 替换它。我想要输出文件:
- 有 NaN 和
- 变量名称包含在输出中。
给定一个包含许多的 Matlab 表,NaN
我如何将此表写为 excel 或 csv 文件,其中 NaN 被空白替换?
我使用以下功能:
T = table(NaN(5,2),'VariableNames',{'A','C'})
writetable(T, filename)
我不想用 zeros 替换它。我想要输出文件:
你只需要xlswrite
那个。它将NaN
s 替换为空白本身。首先使用和table2cell
的组合将表格转换为元胞数组。使用表的属性检索变量名称并用元胞数组填充它们。table2array
num2cell
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
老实说,我认为以您描述的格式输出数据的最直接方法是使用Sardar 在他的回答中所做的xlswrite
那样。但是,如果您真的想使用,我能想到的唯一选择是将表中的每个值封装在一个单元格数组中,并用空单元格替换条目。从这个带有随机数据和值的示例表开始:writetable
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');