【问题标题】:How can I merge this data in MATLAB?如何在 MATLAB 中合并这些数据?
【发布时间】: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)

【问题讨论】:

    标签: matlab merge


    【解决方案1】:

    当前time 值被正确写入但前一个值不正确的原因是因为您在上一次循环迭代中已经将前一个值写入文件,所以没有你改变它的方法。您需要从循环中删除打印并在调整所有 time 值后添加它。

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

    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
    

    【讨论】:

    • 谢谢gnovice..如果我有千行是否可以使用矢量?
    • @Jessy:上面的代码应该可以毫无问题地处理包含数千个元素的向量。不过有一个警告:如果c 有一个紧挨着的,你可能会得到意想不到的结果。例如,time = [20; 10; 10];c = [0; 1; 1]; 将给出time = [30; 0; 0]; 的结果,而不是time = [30; 10; 0];。这样可以吗?
    • @gnovice:谢谢。但我真的需要时间=[30;10;0] :(
    • @Jessy:没问题。我更新了代码,为您提供所需的输出。 ;)
    • @gnovice:谢谢 :) ..但我有一个小问题。新数据的写入格式与原始文件不同..e.g. 'a' 的所有数据首先写在许多列中,而不仅仅是在一列中,'time' 和'c' 类似。
    猜你喜欢
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    相关资源
    最近更新 更多