POliveira
POliveira

Reputation: 196

How to vectorize this Matlab loop

I need some help to vectorize the following operation since I'm a little confused.

So, I have a m-by-2 matrix A and n-by-1 vector b. I want to create a n-by-1 vector c whose entries should be the values of the second column of A whose line is given by the line where the correspondent value of b would fall...

Not sure if I was clear enough. Anyway, the code below does compute c correctly so you can understand what is my desired output. However, I want to vectorize this function since my real n and m are in the order of many thousands.

Note that values of bare non-integer and not necessarily equal to any of those in the first column of A (these ones could be non-integers too!).

m = 5; n = 10;

A = [(0:m-1)*1.1;rand(1,m)]'
b = (m-1)*rand(n,1)

[bincounts, ind] = histc(b,A(:,1))

for i = 1:n
    c(i) = A(ind(i),2);
end

Upvotes: 0

Views: 55

Answers (1)

eigenchris
eigenchris

Reputation: 5821

All you need is:

c = A(ind,2);

Upvotes: 2

Related Questions