Using a vector of indices to add values to a matrix

4 ビュー (過去 30 日間)
Christopher
Christopher 2014 年 3 月 2 日
回答済み: Jos (10584) 2014 年 3 月 5 日
I am trying to vectorize a piece of code which has this form:
for m = 1:1:numel(N)
y = N(m,1);
x = N(m,2);
val = N(m,3);
P(y,x) = P(y,x)+val;
end
So, there is the matrix of column vectors N which hold coordinate information and a value. Using the coordinates the corresponding values are added to the matrix P.
How can this be done efficiently? Thanks.

採用された回答

Paul
Paul 2014 年 3 月 2 日
編集済み: Paul 2014 年 3 月 2 日
xs = N(:,1);
ys = N(:,2);
val = N(:,3);
siz = size(P);
ind = sub2ind(siz,ys,xs);
P(ind) = P(ind)+val.';
  2 件のコメント
Jos (10584)
Jos (10584) 2014 年 3 月 2 日
Note that the addition will not work properly for duplicates of (xs,ys) / ind
Christopher
Christopher 2014 年 3 月 5 日
編集済み: Christopher 2014 年 3 月 5 日
I think I have found that you are right. The result for the loop and the vectorized operation are completely different. Perhaps because there is a lot of repeated indices (thus addition) in my code. Does anyone know of a workaround???

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

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2014 年 3 月 5 日
ACCUMARRAY is, by far, the easiest approach:
N = [1 2 7 ; 1 2 4 ; 2 3 5 ; 2 1 6]
P = accumarray(N(:,1:2),N(:,3))

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by