2012-07-08 40 views
0

的SUMIFS一列的我有這樣另外某些條件在另一個式柱,如Excel

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

矩陣現在我要添加的第二列中的條件是,如果限制= 0,並且間隔= 3和limit = limit + interval,或者換句話說,當列1的值,範圍如0到3,3到6,6到9和9到12時,我必須求和第2列,列的對應值2.

我的解決方案將是這樣的

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

就像我有一個7000x2左右的矩陣。代替範圍,也可以給出序列號。

這只是一個例子。

回答

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 

編輯

如果你需要,而不是在範圍內的數項,它仍然是一個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 
+0

謝謝喬納斯,這是正常工作。 – 2012-07-09 15:28:20

+0

http://stackoverflow.com/questions/11395823/addition-of-one-column-with-certain-condition-in-another-colum-like-sumifs-of-e plz幫助解決這個問題 – 2012-07-09 15:29:15

+0

@DibyenduPal:我已經爲您的計數問題添加了一個解決方案 – Jonas 2012-07-09 16:22:43

相關問題