Using a vector of indices to add values to a matrix
조회 수: 3 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
채택된 답변
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)
2014년 3월 2일
Note that the addition will not work properly for duplicates of (xs,ys) / ind
추가 답변 (1개)
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))
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!