Wednesday, May 20, 2009

Matlab: vector indexing;

OP here.

Q:

I have a reference vector r, and a target vector v, I want to find, for every element in v, the index of first element that is greater than or equal to it in r.

With a for loop it shall look like this:

for k = 1:length(r), idx(k) = find(r >= v(k), 1, 'first'); end
A1 (the 'standard' vectorization):

[dummy,idx] = max(bsxfun(@ge,r(:),v(:).'));

A2 (interesting):

idx = ceil(interp1(r,1:length(r),v));

A3 (same logic as A2 but better):

[dummy, idx] = histc(v,r);
idx = idx+1;

Speed test:

% r = cumsum(rand(100000,1));
% r = r./r(end);
% v = rand(20000,1);


Method 1: % actually slower than the for loop ... memory.
Elapsed time is 6.582422 seconds.

Method 2:
Elapsed time is 0.015725 seconds.

Method 3:
Elapsed time is 0.006501 seconds.

The For loop:
Elapsed time is 4.209633 seconds.


No comments: