[英]Adding value of a vector to another using Octave/Matlab
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?我如何使用 Octave/Matlab 完成此操作?
EDIT: v1 = [1 2 3 4]编辑:v1 = [1 2 3 4]
v2 = [0 0] v2 = [0 0]
indices = [1 2 1 2]指数 = [1 2 1 2]
output = [4 6] 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. v1 的第一个和第三个元素添加到 v2 的索引 1,v1 的第二个和第四个元素添加到 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:您想执行bigVector + toAdd
,将特定索引处的toAdd
元素添加到bigVector
中,指定为:
indices = [1 3 5 7 9];
That is, you want the output vector:也就是说,您需要 output 向量:
[ 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
.特别注意outputVector(indices)
和bigVector(indices)
,它们选择由向量indices
指定的outputVector
和bigVector
的元素。
This should do:这应该做:
for k=unique(indices),
v2(k) = v2(k) + sum(v1(indices==k));
end
It's......它的......
v2 = accumarray(indices, v1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.