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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With