How to count and reduce values in matrix

1 次查看(过去 30 天)
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 个评论
Rik
Rik 2017-5-23
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.
Tiffan
Tiffan 2017-5-23
This my effort so far:
KK = unique(input(:,1));
n = histc(input(:,1),KK);
mm = n(input(:,1));
Dif = input(:,4)./mm;
output1 = [input(:,1) input(:,2) (input(:,3)-Dif)];
Return:
1 3 30
1 1 20
1 4 10
2 3 27.5000000000000
2 4 17.5000000000000
2 1 37.5000000000000
2 9 -2.50000000000000
3 2 20
3 9 30
3 5 40
4 2 54
4 2 64
4 1 14
4 1 29
4 8 84
But, I don't know how to count 3 & 4 for the second part in my question.

请先登录,再进行评论。

采纳的回答

Andrei Bobrov
Andrei Bobrov 2017-5-23
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));

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by