Measure Sum of column if statements are true
조회 수: 4 (최근 30일)
이전 댓글 표시
Panayiotis Christodoulou
2016년 5월 30일
댓글: Panayiotis Christodoulou
2016년 5월 31일
Hi there,
I have a matrix array of 4 columns
first: ID
Second: ShopID
Third: Visits
Forth: 1 or -1
How can I measure the sum of Visits (3rd column) for every ID (1st column) when the 4th column is 1 and how many visits when the 4th column is -1
Thanks
댓글 수: 2
채택된 답변
Ahmed Rashid
2016년 5월 30일
a = [1 1 2 1; 2 2 3 1; 1 1 2 -1; 2 2 1 -1; 3 3 2 1; 1 2 3 1; 1 2 1 -1];
uniqueIds = unique(a(:, 1));
nrOfUniqueIds = length(uniqueIds);
sortedSumOnes = zeros(nrOfUniqueIds, 2); % first column is id second is the sum
sortedSumMinusOnes = zeros(nrOfUniqueIds, 2); % first column is id, second is the sum
for ii = 1:nrOfUniqueIds
sortedSumOnes(ii, :) = [uniqueIds(ii), sum(a((a(:, 4) == 1) & (a(:, 1) == uniqueIds(ii)), 3))];
sortedSumMinusOnes(ii, :) = [uniqueIds(ii), sum(a((a(:, 4) == -1) & (a(:, 1) == uniqueIds(ii)), 3))];
end
Just replace the a matrix with your own matrix
추가 답변 (1개)
Matt Kindig
2016년 5월 30일
There are a couple of ways to do this, but I think the easiest is to use the consolidator function on the File Exchange here:
In that way, the result would be found as
% suppose "M" is your N x 4 matrix
positive = (M(:,4)==1);
negative = (M(:,4)==-1);
[ID, positiveSum] = consolidator(M(positive,1), M(positive,3), @sum);
[ID, negativeSum] = consolidator(M(negative,1), M(negative,3), @sum);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!