Here is my solution:
ordermat = [2; 1; 4; 3; 6]; bigmat = [ 1 10 1 30 1 40 2 1 2 11 3 58 4 2 4 5 ]; %#bigmat = sortrows(bigmat,1); %# keep valid IDs, ord = ordermat( ismember(ordermat,bigmat(:,1)) ); ord = grp2idx(ord); %# starting/ending locations of the different IDs in bigmat startInd = find( diff([0;bigmat(:,1)]) ); endInd = [startInd(2:end)-1; size(bigmat,1)]; %# generate startInd(i):endInd(i) intervals ind = arrayfun(@colon, startInd, endInd, 'UniformOutput',false); %# order then combine the intervals of indices ind = [ind{ord}]; %# get final sorted result finalans = bigmat(ind,:);
I made sure that it handles different cases, for example:
ordermat contains identifiers not found in bigmat : ordermat = [2;1;4;3;6]- not all
bigmat identifiers bigmat represented in ordermat : ordermat = [2;1] - Identifiers are not sequential and / or do not start with 1:
ordermat=ordermat+10; bigmat=bigmat+10; ordermat=ordermat+10; bigmat=bigmat+10;
source share