本文介绍了如何在MATLAB中执行此累加和运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为第1列中的每个字符串计算以下dat.txt的第2列中值的累加和.所需的输出显示为dat2.txt:

I want to calculate a cumulative sum of the values in column 2 of dat.txt below for each string of ones in column 1. The desired output is shown as dat2.txt:

dat.txt  dat2.txt
1 20     1 20  20   % 20 + 0
1 22     1 22  42   % 20 + 22
1 20     1 20  62   % 42 + 20
0 11     0 11  11
0 12     0 12  12
1 99     1 99  99   % 99 + 0   
1 20     1 20  119  % 20 + 99
1 50     1 50  169  % 50 + 119

这是我的最初尝试:

fid=fopen('dat.txt');
A  =textscan(fid,'%f%f');
in =cell2mat(A); 
fclose(fid);

i = find(in(2:end,1) == 1 & in(1:end-1,1)==1)+1;
out = in;
cumulative =in;
cumulative(i,2)=cumulative (i-1,2)+ cumulative(i,2);

fid = fopen('dat2.txt','wt');
format short g;
fprintf(fid,'%g\t%g\t%g\n',[out cumulative(:)]');
fclose(fid);

推荐答案

这里是使用功能 CUMSUM DIFF 以及逻辑索引以产生所需的结果:

Here's a completely vectorized (albeit somewhat confusing-looking) solution that uses the functions CUMSUM and DIFF along with logical indexing to produce the results you want:

>> data = [1 20;...  %# Initial data
           1 22;...
           1 20;...
           0 11;...
           0 12;...
           1 99;...
           1 20;...
           1 50];
>> data(:,3) = cumsum(data(:,2));       %# Add a third column containing the
                                        %#   cumulative sum of column 2
>> index = (diff([0; data(:,1)]) > 0);  %# Find a logical index showing where
                                        %#   continuous groups of ones start
>> offset = cumsum(index.*(data(:,3)-data(:,2)));  %# An adjustment required to
                                                   %#   zero the cumulative sum
                                                   %#   at the start of a group
                                                   %#   of ones
>> data(:,3) = data(:,3)-offset;        %# Apply the offset adjustment
>> index = (data(:,1) == 0);            %# Find a logical index showing where
                                        %#   the first column is zero
>> data(index,3) = data(index,2)        %# For each zero in column 1 set the
                                        %#   value in column 3 to be equal to
data =                                  %#   the value in column 2

     1    20    20
     1    22    42
     1    20    62
     0    11    11
     0    12    12
     1    99    99
     1    20   119
     1    50   169

这篇关于如何在MATLAB中执行此累加和运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 21:11