How to count and reduce values in matrix

1 回表示 (過去 30 日間)
Tiffan
Tiffan 2017 年 5 月 23 日
コメント済み: Tiffan 2017 年 5 月 23 日
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));
  1 件のコメント
Tiffan
Tiffan 2017 年 5 月 23 日
Thank you @Andrei Bobrov

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by