How to count and reduce values in matrix
1 view (last 30 days)
Show older comments
Matrix input:
input = [
1 3 50 60
1 1 40 60
1 4 30 60
2 3 40 50
2 4 30 50
2 1 50 50
2 9 10 50
3 2 20 0
3 9 30 0
3 5 40 0
4 2 50 -20
4 2 60 -20
4 1 10 -20
4 1 25 -20
4 8 80 -20
];
% there are three 1, so 60/3, there are four 2, so 50/4, there are three 3, so 0/3 and there are five 4, so -20/5.
% 50-60/3 = 30
% 40-60/3 = 20
% 30-60/3 = 10
Based on the similar arrays in the first column, I want to find for example how many 1 are there. Then divide the forth column by that (for example 1 is 3 here) and then reduce the amount from the third column. The first output should be:
output1 = [
1 3 30
1 1 20
1 4 10
2 3 27.5
2 4 17.5
2 1 37.5
2 9 -2.5
3 2 20
3 9 30
3 5 40
4 2 54
4 2 64
4 1 14
4 1 29
4 8 84
];
For the second output, I want the same process, but instead of counting all same numbers in the first column, this time just look at the second column and count if there is 3 and 4 (for every unique number in the first column).
output2 = [
1 3 20
1 1 40
1 4 0
2 3 15
2 4 5
2 1 50
2 9 10
3 2 20
3 9 30
3 5 40
4 2 50
4 2 60
4 1 10
4 1 25
4 8 80
];
% for "1", there are two 3&4, so 60/2
% 50-60/2 = 20
% 30-60/2 = 0
2 Comments
Rik
on 23 May 2017
What have you tried? Have you looked at functions like unique? As someone said elsewhere: the community spends hours to help you, or seconds to ignore you. Show that you have put in some effort, and people are more likely to put in more effort helping.
Accepted Answer
Andrei Bobrov
on 23 May 2017
a = input;
ii = accumarray(a(:,1),1);
out1 = [a(:,1:2),a(:,3) - a(:,end)./ii(a(:,1))];
t = ismember(a(:,2),3:4);
i1 = accumarray(a(:,1),t);
out2 = a(:,1:3);
out2(t,3) = out2(t,3) - a(t,end)./i1(a(t,1));
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!