【发布时间】:2015-11-24 03:30:08
【问题描述】:
在下面的示例文本文件中,如果第 3 列包含 1,则第 2 列的相应数据应与第 2 列中上一行的数据合并。例如,第 2 行中的40 应添加到第 1 行的10,然后第 2 行应设置为0(如修改后的示例文本文件所示)。我下面代码的问题是它只记录了当前数据time(i,1)的变化,而不记录之前数据的变化。
original.txt
a time c
1 10 0
2 40 1
3 20 0
4 11 0
5 40 1
modified.txt
a time c
1 50 0
2 0 0
3 20 0
4 51 0
5 0 0
fid=fopen('data.txt');
A=textscan(fid,'%f%f%f');
a =A{1};
time=A{2};
c =A{3};
fclose(fid);
fid=fopen('newData.txt','wt');
for i=1:size(a)
if c(i,1)==1
time(i-1,1)=time(i,1)+time(i-1,1); % merge the time of the current and the previous
time(i,1) =0; %set the time to 0
array = []; %empty the array
array = [a(i,1) time c(i,1)]; add new data
format short g;
fprintf(fid,'%g\t %g\t %g\n',array);
end
fclose(fid)
【问题讨论】: