How to find first two maximum number in the matrix

2 ビュー (過去 30 日間)
Moe
Moe 2015 年 10 月 19 日
編集済み: Andrei Bobrov 2015 年 10 月 23 日
Hello everyone,
I have the following matrix A (right table):
A = [1248,30,12;1248,20,13;1248,5,14;177,5,12;177,25,13;230,10,14;230,40,15;274,60,12;274,5,14];
I want to find the matrix B (left table) in the way that first, check the column "ID" to find the similar ID, then find the first two max number and finally find the "PE" related to the found first two max number. For example, first it will find that ID = 1248 has three repetitions. Then, from TE, it will find that 30 and 20 are the first two max numbers. And finally, it will find 12 (for max 30) and 13 (for max 20). Can anyone help how to search for that unique id

採用された回答

Andrei Bobrov
Andrei Bobrov 2015 年 10 月 23 日
編集済み: Andrei Bobrov 2015 年 10 月 23 日
[a,~,c] = unique(A(:,1),'stable');
a0 = sortrows([c,A(:,2:end)],[1,-(2:3)]);
i1 = bsxfun(@plus,find([1;diff(A(:,1))~=0]),0:1)';
out = [a,reshape(permute(reshape(a0(i1,2:end),2,[],2),[1,3,2]),4,[])'];
or
a = unique(A(:,1),'stable');
n = numel(a);
out = zeros(n,5);
for ii = 1:n
l0 = a(ii) == A(:,1);
b = sortrows(A(l0,2:end),-(1:2));
out(ii,:) = [a(ii),reshape(b(1:2,:),1,[])];
end

その他の回答 (1 件)

TastyPastry
TastyPastry 2015 年 10 月 19 日
Assuming there are at least 2 values for TE/PE for each ID:
uniqueVals = unique(A(:,1),'stable');
output = zeros(numel(uniqueVals),5);
for i = 1:numel(uniqueVals)
mask = A(:,1) == uniqueVals(i);
[sorted,ind] = sort(A(mask,2),'descend');
PE = A(mask,3);
newRow = [uniqueVals(i) sorted(1:2) PE(ind)];
output(i,:) = newRow;
end
  2 件のコメント
Moe
Moe 2015 年 10 月 20 日
Hi TastyPastry, the code is given the following error:
Error using horzcat
CAT arguments dimensions are
not consistent.
TastyPastry
TastyPastry 2015 年 10 月 23 日
newRow = [uniqueVals(i) sorted(1:2)' PE(ind(1:2))'];
This code still only works if each ID has two values of TE and PE associated with it. It will error on the last line ID = 811 as shown above.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by