Reputation: 923
I have a master array and a query array:-
master_array=[2;5;3;7;1];
query_array=[1;3];
All elements of query array will be a member of the master array. That is a rule. I have to find the order of all the elements of query array as prescribed by the master array.
I could naively do this:-
a=[];
for i=query_array'
a=[a;i,find(master_array==i)];
end
a=sortrows(a,2);
order_array=a(:,1);
Is a more efficient solution available?
Upvotes: 1
Views: 26
Reputation: 125874
You could use intersect
:
order_array = intersect(master_array, query_array, 'stable');
Or you could use ismember
:
order_array = master_array(ismember(master_array, query_array));
Upvotes: 2
Reputation: 23685
This solution takes almost 70% less time in my benchmarks:
[~,idx] = ismember(master_array,query_array);
order_array = query_array(idx(idx > 0));
For more information about the ismember
function, refer to this page of the official Matlab documentation.
Upvotes: 1