Tuesday, June 16, 2009

Matlab: vector indexing.

OP here.

Q:
I have a random vector r of size 50000 x 1, and a strictly decreasing measuring vector d of size 300 x 1. I want for each element in r, find the indices of the first value in d that is smaller than it. I tried these codes but it is too slow. Is there a vectorized solution?

n = 50000;
r = rand(n,1);
d = linspace(1,0,300);
idx = nan(n,1);

for k = 1:n
idx(k) = find(r(k) > d, 1, 'first');
end


A:

[dump,idx] = histc(r,d(end:-1:1));
idx = length(d)-idx+1;

No comments: