在另一个列中添加一个具有一定条件的列,如excel的sumif

0 matlab sum addition sumifs

我有一个像这样的矩阵

A=[ 1 2; 2 3; 3 4; 4 5; 5 6; 6 8; 7 9; 8 5; 9 4]
Run Code Online (Sandbox Code Playgroud)

现在我想添加第二列,条件是如果limit = 0,interval = 3和limit = limit + interval,或者换句话说,我必须在第1列的值时对第2列求和,范围如0到3 ,3到6,6到9和9到12,我想要第2列的相应值的总和.

我的解决方案就是这样

range- sum
0 to 3 9
3 to 6 19
6 to 9 18
Run Code Online (Sandbox Code Playgroud)

就像我有一个大约7000x2的矩阵.也可以给出序列号代替范围.

这只是一个例子.

Jon*_*nas 5

这是ACCUMARRAY的工作.首先,构造一个应该加在一起的值的索引数组,然后调用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
Run Code Online (Sandbox Code Playgroud)

编辑

如果你需要计算范围内的条目,它仍然是一个工作accumarray,只是你没有积累到一个总和,而是直方图.

%# 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
Run Code Online (Sandbox Code Playgroud)