How do I efficiently add values of same indices to a vector?

7 ビュー (過去 30 日間)
Tzaki
Tzaki 2022 年 1 月 25 日
編集済み: Tzaki 2022 年 1 月 25 日
Hello, I am pretty much new to MATLAB.
I have a large vector vec1=[2 7 4 3], a small vector vec2=[1 10 100], and an index vector ind=[1 2 1] (numel(vec2)=numel(idx)). I want to add each element of vec2 to the element of vec1 that is specified by ind. In this example, I want ans=[103 17 4 3].
Intuitively, I first tried
vec1(ind) = vec1(ind) + vec2, (1)
but this gave me ans=[102 17 4 3], telling me that the duplicates in ind were not considered.
To get around this, I added a for loop before (1) to remove the duplicates, which works fine but takes too long.
I would like to know if there is an efficient way to solve this.

採用された回答

Matt J
Matt J 2022 年 1 月 25 日
編集済み: Matt J 2022 年 1 月 25 日
vec1=vec1+accumarray(ind(:),vec2(:),size(vec1));
  1 件のコメント
Tzaki
Tzaki 2022 年 1 月 25 日
Thank you very much, It seems that yours works perfectly!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by