Using a vector of indices to add values to a matrix
2 次查看(过去 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 个评论
采纳的回答
更多回答(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!