我的代码终止了一个现有的.csv文件。它加载现有的.csv文件,写入新信息,然后再次保存:
file = directory/test.csv
%Load data from old table
alpha1 = readtable(file)
alpha2 = alpha1.Variables;
alpha = array2table(alpha2);
%Get new data
beta = array2table(newdata);
beta.Properties.VariableNames = {'alpha21' 'alpha22' 'alpha23' 'alpha24' };
%Merge old and new data then save
merge = [alpha;beta];
writetable(merge,file,'WriteVariableNames',0);
表格的第一列是文件号:
2×4 table
alpha21 alpha22 alpha23 alpha24
_______ __________ __________ __________
1 2.2204e-14 2.2204e-14 2.2204e-14
2 2.2204e-14 2.2204e-14 2.2204e-14
beta =
2×4 table
alpha21 alpha22 alpha23 alpha24
_______ __________ __________ __________
4 2.2204e-14 2.2204e-14 2.2204e-14
5 2.2204e-14 2.2204e-14 2.2204e-14
当合并两个表时,我希望第一列的编号来确定表中的行位置,从而产生以下结果:
5×4 table
alpha21 alpha22 alpha23 alpha24
_______ __________ __________ __________
1 2.2204e-14 2.2204e-14 2.2204e-14
2 2.2204e-14 2.2204e-14 2.2204e-14
NaN or zero
4 2.2204e-14 2.2204e-14 2.2204e-14
5 2.2204e-14 2.2204e-14 2.2204e-14
此外,如果行已经被填充,我希望它被过度填充。
感谢
您可以使用:
% Simulated data
Nalpha=20;
Nbeta=25;
alpha=table( (1:Nalpha).', randn(Nalpha,1), randn(Nalpha,1), randn(Nalpha,1), ...
'VariableNames', {'alpha21', 'alpha22', 'alpha23', 'alpha24'} );
beta=table( (1:Nbeta).', randn(Nbeta,1), randn(Nbeta,1), randn(Nbeta,1), ...
'VariableNames', {'alpha21', 'alpha22', 'alpha23', 'alpha24'} );
alpha( randperm(Nalpha,round(Nalpha/4)), : )=[]; %discard some rows
beta( randperm(Nbeta,round(Nbeta/4)), : )=[]; %discard some rows
% Merge tables
N=max(max(alpha.alpha21),max(beta.alpha21));
varnames=alpha.Properties.VariableNames;
gamma=[ (1:N).' nan([N numel(varnames)-1]) ];
gamma=array2table( gamma, 'VariableNames', varnames );
gamma(alpha.alpha21,:)=alpha;
gamma(beta.alpha21,:)=beta; %have any values in beta take precedence over those in alpha