Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove rows with same first column and min second column

Tags:

arrays

matlab

I have a two column list. The first column are subject numbers, the second session numbers (i.e. when the subject comes in the second time, the session number is 2, and so forth for every visit).

SubMasterList = [6004 1; 6004 2; 6008 1; 6008 2; 6010 1; 6012 1; 6012 2; 6012 3]

I would like SubMasterList to only contain 1 row of the subject with the greatest session number (column 2). So as to appear to be:

SubMasterList = [6004 2; 6008 2; 6010 1; 6012 3]
like image 321
Shane Murphy Avatar asked Jun 15 '26 21:06

Shane Murphy


2 Answers

You can use sortrows after which you extract indices from that array using the second output of unique

SubMasterList = [6004 1; 6004 2; 6008 1; 6008 2; 6010 1; 6012 1; 6012 2; 6012 3];
tmp = sortrows(SubMasterList,-2); %sort, with descending order to ensure the highest number is on top
[~,idx,~]=unique(tmp(:,1)); %extract indices
Result = tmp(idx,:) %index the sorted array to obtain the result

Result =
        6004           2
        6008           2
        6010           1
        6012           3
like image 139
Adriaan Avatar answered Jun 17 '26 11:06

Adriaan


What you want is almost the definition of accumarray :-) Just use unique to get labels based on the first column of your matrix, and pass that as first input to accumarray:

[x, ~, u] = unique(SubMasterList(:,1));
y = accumarray(u, SubMasterList(:,2), [], @max);
result = [x y];
like image 41
Luis Mendo Avatar answered Jun 17 '26 09:06

Luis Mendo