poster
2019-12-10, 20:41
在下面的示例文本文件中,如果第3列包含1 ,则应将第2列的相应数据与第2列中的上一行数据合并。例如,第2行中的40应该添加到第10行中1,然后将第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)
回答:
当前time值已正确写入但前一个time值未正确写入的原因是,因为您已在上一个循环迭代中将前一个值写入文件,所以无法更改它。您需要从循环中删除打印,并在调整所有time值后添加。
您还可以通过使用FIND (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/find.html)函数而不是for循环来利用矢量化。您还只需要调用FPRINTF (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fprintf.html)即可输出所有数据。尝试这个:
a = [1; 2; 3; 4; 5]; %# Sample data time = [10; 40; 20; 11; 40]; %# Sample data c = [0; 1; 0; 0; 1]; %# Sample data index = find(c == 1); %# Find indices where c equals 1 temp = time(index); %# Temporarily store the time values time(index) = 0; %# Zero-out the time points time(index-1) = time(index-1)+temp; %# Add to the previous time points c(index) = 0; %# Zero-out the entries of c fid = fopen('newData.txt','wt'); %# Open the file fprintf(fid,'%g\t %g\t %g\n',[a time c].'); %'# Write the data to the file fclose(fid); %# Close the file
更多&回答... (https://stackoverflow.com/questions/3071558)
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)
回答:
当前time值已正确写入但前一个time值未正确写入的原因是,因为您已在上一个循环迭代中将前一个值写入文件,所以无法更改它。您需要从循环中删除打印,并在调整所有time值后添加。
您还可以通过使用FIND (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/find.html)函数而不是for循环来利用矢量化。您还只需要调用FPRINTF (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fprintf.html)即可输出所有数据。尝试这个:
a = [1; 2; 3; 4; 5]; %# Sample data time = [10; 40; 20; 11; 40]; %# Sample data c = [0; 1; 0; 0; 1]; %# Sample data index = find(c == 1); %# Find indices where c equals 1 temp = time(index); %# Temporarily store the time values time(index) = 0; %# Zero-out the time points time(index-1) = time(index-1)+temp; %# Add to the previous time points c(index) = 0; %# Zero-out the entries of c fid = fopen('newData.txt','wt'); %# Open the file fprintf(fid,'%g\t %g\t %g\n',[a time c].'); %'# Write the data to the file fclose(fid); %# Close the file
更多&回答... (https://stackoverflow.com/questions/3071558)