quick search in two vectors
Show older comments
There are 2 vectors with the same length va and vb ; We want to find out the index i where va(i) = m and vb(i) = n. Currently, we have 2 possible solutions:
1) index = find(va == m & vb == n);
2) mask = va == m; local_mask = vb(mask) == n; %we only need to look at part of vb here. msk = find(msk); index = msk(local_mask);
We think (after testing) that 2) is faster than 1).
Since we are intensively update va and vb, and make query every time, 2) is not good enough.
The length of va and vb is more than 1 million. They are not sorted. m and n are not constant.
So, is there any better solution? Thank you very much.
PS。construct sparse matrix or a hash table is too expensive for us.
Accepted Answer
More Answers (2)
per isakson
on 16 May 2012
strfind is a bit faster than find with whole numbers (floating integers, flints). The difference used to be larger. With R2012a 64bit:
>> n= randi( 1e5, [ 1, 1e6 ] );
tic, ix = find( n==17 ); toc
tic, ixsf = strfind( n, 17 ); toc
Elapsed time is 0.004021 seconds.
Elapsed time is 0.001884 seconds.
>> ix==ixsf
ans =
1 1 1 1 1 1 1 1 1 1 1 1
Sean de Wolski
on 16 May 2012
0 votes
You might want to look at ismember() with the 'rows' flag. Keep column vectors vb, va together in one matrix as v. I don't know if this will be faster or not.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!