gpbdr13
gpbdr13

Reputation: 115

Matlab operation without loops

I have a matrix distance = [d11,d12,d13,d14;d15;...;dn1,dn2,dn3,dn4,dn5]; and a vector index(n,1). The value of index are between 1 and 5.

I want to get the sum of the distance according to the index if a vector R(1,5).

An example :

distance = [1,2,4,1,2 ; 4,5,6,1,6 ; 7,8,9,5,8] and index = [1;1;3]

So, I want R(1) = 1+4 = 5, R(2) = 0, R(3) = 9, and R(4) = R(5) = 0

The condition is to not use a loop over 1:5 with a if condition in order to minimise the time of execution if there are billions of points.

Maybe it is possible with arrayfun, but I don't succeed.

Best regards

Upvotes: 1

Views: 49

Answers (1)

hbaderts
hbaderts

Reputation: 14371

To find out which elements you have to sum up, you can use the bsxfun to create a matrix containing a 1 if the value is relevant, and a 0 otherwise. This can done with

bsxfun(@eq, index, 1:5)

which will create a vector [1, 2, 3, 4, 5] and do an element-wise comparison between index and that vector. The result of this function is

ans =

     1     0     0     0     0
     1     0     0     0     0
     0     0     1     0     0

Now you can multiply this matrix with the distance matrix (element-wise!) and finally sum over each column:

>> R = sum(bsxfun(@eq, index, 1:5) .* distance, 1);

which results in

R =

     5     0     9     0     0

Upvotes: 1

Related Questions