addition of one column with certain condition in another colum, like sumifs of excel

梦想与她 提交于 2019-12-02 19:29:23

问题


I have a matrix like this

A=[ 1 2; 2 3; 3 4; 4 5; 5 6; 6 8; 7 9; 8 5; 9 4]

Now I want to add a second column the condition is that if limit=0, and interval=3 and limit=limit+interval, or in other words, I have to sum column 2 when values of column 1, ranges like 0 to 3, 3 to 6, 6 to 9, and 9 to 12, and i want sum of corresponding values of column 2.

my solution will be like that

range- sum
0 to 3 9
3 to 6 19
6 to 9 18

like that I have a matrix of around 7000x2. In place of range just serial no may also be given.

This is just an example.


回答1:


This is a job for ACCUMARRAY. First, you construct an array of indices of the values that should be added together, then you call accumarray:

%# create test data
A=[ 1 2; 2 3; 3 4; 4 5; 5 6; 6 8; 7 9; 8 5; 9 4];

%# create indices from first column
%# if you have indices already, you can use them directly
%#   or you can convert them to consecutive indices via grp2idx
groupIdx = ceil(A(:,1)/3); %# 0+ to 3 is group 1, 3+ to 6 is group 2, etc

%# sum
result = accumarray(groupIdx,A(:,2),[],@sum)

result =
     9
    19
    18

EDIT

If you need instead to count entries within the ranges, it is still a job for accumarray, only that you don't accumulate into a sum, but into a histogram.

%# use test data, groupIdx from above
A=[ 1 2; 2 3; 3 4; 4 5; 5 6; 6 8; 7 9; 8 5; 9 4];
groupIdx = ceil(A(:,1)/3); %# 0+ to 3 is group 1, 3+ to 6 is group 2, etc

%# find values to count
values2count = unique(A(:,2));

%# count the values
countsPerRange = accumarray(groupIdx,A(:,2),[],@(x){hist(x,values2count)})


%# inspect the counts for range #1
 [values2count,countsPerRange{1}']

ans =

     2     1
     3     1
     4     1
     5     0
     6     0
     8     0
     9     0


来源:https://stackoverflow.com/questions/11385732/addition-of-one-column-with-certain-condition-in-another-colum-like-sumifs-of-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!