Find rows of a matrix corresponds to accumarray results

조회 수: 1 (최근 30일)
Maii
Maii 2020년 2월 24일
편집: Jon 2020년 2월 24일
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.

답변 (1개)

Jon
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.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by