LarrySnyder610
LarrySnyder610

Reputation: 2397

MATLAB "element-wise" logical indexing

Suppose I have an array

d1 = 0 : 0.5 : 10

(d1 represents a discretization of a random variable, FWIW.) Suppose I have another array, e.g.,

d2 = [0.35 pi 4.2731]

Now I want an array that gives me the index of the closest element in d1 to each element in d2 -- actually I'd even take the largest element in d1 that is less than the element of d2, i.e., I want

ind = [2 8 10]

How can I do this efficiently? If I only needed this for a single element of d2, I could do something like

dindex = 1:length(d1);
ind = min(dindex(d1 >= d2(3)))

But if I want to do it for all elements in d2, I can't say ind = min(dindex(d1 >= d2)). What's the solution? And thanks.

Upvotes: 2

Views: 356

Answers (2)

LarrySnyder610
LarrySnyder610

Reputation: 2397

On second thought, since d1 has equally-spaced elements, I think a cleaner way is this:

dlo = d1(1);
dhi = d1(length(d1));
ddelta = d1(2) - d1(1);

ind = round((min(dhi, max(dlo, d2)) - dlo) / ddelta) + 1;

(The min and max ensure d2 entries are within the range of d1.) This is a lot faster -- 0.038s on my 4008 calls.

Thanks everyone...this was quite a positive first experience on this site.

Upvotes: 1

Divakar
Divakar

Reputation: 221564

You might prefer faster and vectorized approach with bsxfun -

[~,ind] = min(abs(bsxfun(@minus,d1,d2')),[],2)

Upvotes: 2

Related Questions