1

I have a vector of values I need to add to a second vector at indices specified by another vector. How do I accomplish this using Octave/Matlab?

EDIT: v1 = [1 2 3 4]

v2 = [0 0]

indices = [1 2 1 2]

output = [4 6]

The first and third elements of v1 are added to index 1 of v2, and second and fourth element of v1 are added to second element of v2.

1
  • 1
    Could you please give a small reproducible example of all your vectors (& desired output)? It would make it easier for us to understand what you mean. Commented Apr 11, 2012 at 4:46

3 Answers 3

2

I think this is what you mean (if you provide a small example in your question it's easier to understand).

You have a vector of values

toAdd = 1:5; 

You have a second, bigger vector:

bigVector = 1:10; 

You want to do bigVector + toAdd, where you add the elements of toAdd at specific indices into bigVector, specified by:

indices = [1 3 5 7 9]; 

That is, you want the output vector:

[ bigVector(1)+toAdd(1); bigVector(2); bigVector(3)+toAdd(2); bigVector(4); bigVector(5)+toAdd(3); .... ] 

In that case, you can do the following:

outputVector = bigVector; outputVector(indices) = bigVector(indices) + toAdd; 

In particular, notice the outputVector(indices) and bigVector(indices), which selects the elements of outputVector and bigVector specified by the vector indices.

Sign up to request clarification or add additional context in comments.

Comments

1

This should do:

for k=unique(indices), v2(k) = v2(k) + sum(v1(indices==k)); end 

3 Comments

The question is a bit unclear but it looks like you won't need to add the sum to v2(k) so just: for k=unique(indices), v2(k) = sum(v1(indices==k)); end
In the question it says "The first and third elements of v1 are added to index 1 of v2". So v2 might have different initial values even though it is zero in this case.
I agree - but It could mean that they are added to each other and then placed in index 1 etc... Either way I agree with your solution.
0

It's......

v2 = accumarray(indices, v1) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.