フィルターのクリア

group an array according a condition

3 ビュー (過去 30 日間)
eric capnu
eric capnu 2017 年 8 月 9 日
コメント済み: eric capnu 2017 年 9 月 1 日
Hi everyone
i have an array like this
A=
2 10 10.1 12 14 110
2 10.1 11 12 15 145
3 12 12 12 24 223
3 12 11.4 11 23 100
3 10 12 20 18 211
4 9 23 11 11 98
I want to create a new B array where i get the maximum value of each column according to the first column value
B=
2 10.1 11 12 15 145
3 12 12 20 24 223
4 9 23 11 11 98
i don´t want to use loops. is there a way to do it by using just matlab functions?
thanks in advance

採用された回答

Andrei Bobrov
Andrei Bobrov 2017 年 8 月 9 日
編集済み: Andrei Bobrov 2017 年 8 月 10 日
B_table = varfun(@max,array2table(A),'GroupingVariables','A1')
or
B = splitapply(@(x)max(x,[],1),A,findgroups(A(:,1)));
or
g = findgroups(A(:,1)); % or >> [~,~,g] = unique(A(:,1))
[ii,jj] = ndgrid(g,1:size(A,2));
B = accumarray([ii(:),jj(:)],A(:),[],@max);
  2 件のコメント
John BG
John BG 2017 年 8 月 10 日
編集済み: John BG 2017 年 8 月 10 日
and then back to array
B=table2array(Btable)
B =
2.0000 2.0000 10.1000 11.0000 12.0000 15.0000 145.0000
3.0000 3.0000 12.0000 12.0000 20.0000 24.0000 223.0000
4.0000 1.0000 9.0000 23.0000 11.0000 11.0000 98.0000
no need for the frequencies
B(:,2)=[]
B =
2.0000 10.1000 11.0000 12.0000 15.0000 145.0000
3.0000 12.0000 12.0000 20.0000 24.0000 223.0000
4.0000 9.0000 23.0000 11.0000 11.0000 98.0000
eric capnu
eric capnu 2017 年 9 月 1 日
thanks mates. that was very useful... and, what if instead of @max it would be the last element or the first element of the range?

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

その他の回答 (1 件)

Stephen23
Stephen23 2017 年 8 月 9 日
編集済み: Stephen23 2017 年 8 月 9 日
You could use accumarray:
A = [
2 10 10.1 12 14 110
2 10.1 11 12 15 145
3 12 12 12 24 223
3 12 11.4 11 23 100
3 10 12 20 18 211
4 9 23 11 11 98];
%
[~,~,X] = unique(A(:,1));
V = 1:size(A,1);
fun = @(r){max(A(r,:),[],1)};
C = accumarray(X,V(:),[],fun);
Z = vertcat(C{:})
produces this:
Z =
2.0000 10.1000 11.0000 12.0000 15.0000 145.0000
3.0000 12.0000 12.0000 20.0000 24.0000 223.0000
4.0000 9.0000 23.0000 11.0000 11.0000 98.0000

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by