5

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?

1 Answer 1

8

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Would this still work if both A and B were not the same length?
Yes, but there has to be an one-to-one mapping between the indices left and right, or in this case, the index vector indexB used for B.x and the index vector [1:n] used for A.x. And obviously, the elements the indices refer to, need to exist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.