title: How can I merge this data in MATLAB?
body: <p>In the sample text file below, if column 3 contains a <code>1</code> then the corresponding data of column 2 should be merged with the data of the previous row in column 2. For example, the <code>40</code> in row 2 should be added to the <code>10</code> in row 1, then row 2 should be set to <code>0</code> (as shown in the modified sample text file). The problem with my code below is that it only records changes in the current data <code>time(i,1)</code> but not the changes made for the previous data.</p>
  
  <pre><code>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)
  </code></pre>