Filter löschen
Filter löschen

Measure Sum of column if statements are true

1 Ansicht (letzte 30 Tage)
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 Kommentare
the cyclist
the cyclist am 30 Mai 2016
Do you want the sum of each ID separately, or all IDs summed together?
Panayiotis Christodoulou
Panayiotis Christodoulou am 30 Mai 2016
each id separetely

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Ahmed Rashid
Ahmed Rashid am 30 Mai 2016
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

Weitere Antworten (1)

Matt Kindig
Matt Kindig am 30 Mai 2016
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);

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by