Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vectorize for loop with custom index

I'm new to Matlab, so I'm not sure if this is possible. I have a simple for-loop:

for i=1:n
    B.x(indexB(i)) += A.x(i);
end

Where A.x and B.x are two vectors of length n, and indexB is a vector of length n that contains the appropriate mapping from elements in A.x to B.x.

Is it possible to vectorize this loop?

like image 360
Wesley Tansey Avatar asked Oct 02 '12 21:10

Wesley Tansey


1 Answers

I think so, following this example:

a = [1 2 3 4 5];
b = a;
idx = [5 4 3 2 1];
a(idx)  = a(idx) + b(1:5);

Which should give:

a =

 6     6     6     6     6

So in your case, if indexB has size n you can write:

B.x(indexB) = B.x(indexB) + A.x(1:n);

And otherwise:

B.x(indexB(1:n)) = B.x(indexB(1:n)) + A.x(1:n);
like image 108
Maurits Avatar answered Oct 07 '22 20:10

Maurits