![]() |
如何在MATLAB中执行此累计和?
我想为下面第1列中的每个字符串计算dat.txt 2列中值的累积总和。所需的输出显示为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); [B]回答:[/B] 这是一个完全矢量化的(尽管看上去有些令人困惑)解决方案,该解决方案使用[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cumsum.html"]CUMSUM[/URL]和[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/diff.html"]DIFF[/URL]函数以及[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/math/f1-85462.html#bq7egb6-1"]逻辑索引[/URL]来生成所需的结果: >> 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 [url=https://stackoverflow.com/questions/3101893]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 01:10。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.