Filter löschen
Filter löschen

Find rows of a matrix corresponds to accumarray results

3 Ansichten (letzte 30 Tage)
Maii
Maii am 24 Feb. 2020
Bearbeitet: Jon am 24 Feb. 2020
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.

Antworten (1)

Jon
Jon am 24 Feb. 2020
Bearbeitet: Jon am 24 Feb. 2020
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.

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by