Find rows of a matrix corresponds to accumarray results
1 回表示 (過去 30 日間)
古いコメントを表示
Hi
I have a matrix with 4 columns.
for rows that the 1st column is the same , check the 4th column and keep the row with maximum 4th column value.
for example
A=[ 4 5 6 7; 3 6 7 0 ; 4 1 9 3;1 2 3 4 ; 7 1 5 6; 3 1 4 3]
and I like to have output as
out=[ 4 5 6 7 ;1 2 3 4 ; 7 1 5 6;3 1 4 3]
I used accumarray and it gave me [7 4 6 3], but I dont know how to call the rows that their 4th column values are the same.
just note that, In my real code the number of rows of matrix A will be different in each iteration and I should run code later for 10000 times.
Thank you so much for your help in advance.
0 件のコメント
回答 (1 件)
Jon
2020 年 2 月 24 日
編集済み: Jon
2020 年 2 月 24 日
I was having a little difficulty understanding the description of your problem but I think this accomplishes what you are trying to do.
% generate test data
A = randi(5,100,4); % random matrix with max value of 5
% find the unique column one values
uniqueVals = unique(A(:,1));
% loop through unique values
numUnique = length(uniqueVals); % number of unique values
out = zeros(numUnique,4); % preallocate array to hold results
for k = 1:numUnique
% find rows where this unique value occurs
idx = find(A(:,1)== uniqueVals(k));
% for the rows with this unique value in first column find the one
% with the maximum value in the last column and just keep that row
[~,imax] = max(A(idx,4));
% just keep that row
out(k,:) = A(idx(imax),:);
end
Note that if there is more than one row that has the same element in the first column and the same maximum value in the fourth column then the answer returned in the out array will not be unique.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!