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.
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
.
This should do:
for k=unique(indices),
v2(k) = v2(k) + sum(v1(indices==k));
end
It's......
v2 = accumarray(indices, v1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.