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]
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
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With