如何在MATLAB中合并这些数据? [英] How can I merge this data in MATLAB?

查看:896
本文介绍了如何在MATLAB中合并这些数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例文本文件中,如果第3列包含1,则应将第2列的相应数据与第2列中的上一行数据合并.例如,第2行中的40应该如果将其添加到第1行的10中,则应将第2行设置为0(如修改后的示例文本文件中所示).我下面的代码的问题在于,它仅记录当前数据time(i,1)中的更改,而不记录对先前数据所做的更改.

In the sample text file below, if column 3 contains a 1 then the corresponding data of column 2 should be merged with the data of the previous row in column 2. For example, the 40 in row 2 should be added to the 10 in row 1, then row 2 should be set to 0 (as shown in the modified sample text file). The problem with my code below is that it only records changes in the current data time(i,1) but not the changes made for the previous data.

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值之后添加.

The reason the current time value is written properly but the previous one isn't is because you have already written the previous one to the file on the previous loop iteration, so there is no way for you to change it. You need to remove the printing from within the loop and add it after you adjust all of the time values.

您还可以通过使用 FIND来利用矢量化的优势函数而不是for循环.您还只需要一次调用 FPRINTF 即可输出所有数据.试试这个:

You can also take advantage of vectorization by using the FIND function instead of a for loop. You also only need one call to FPRINTF to output all the data. Try this:

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

这篇关于如何在MATLAB中合并这些数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆