Avoid for loop on sum on given indexes, use accumarray?

Hi,
I'm trying to get rid of the for loop on the follwoing code:
S=zeros(100,50);
V=rand(1,50);
Index=round(50*rand(1,50))
for i=1:50
S(:,Index(i))=S(:,Index(i))+V(i);
end
I probably need to use accumarray but I cannot figure how.
Thanks a lot

2 个评论

Why are you creating 100 rows when you do the same thing to all of them? Why not create one row with the values and later replicate to 100 copies?
It is a simplified version of my problem.
A more accurate one would be:
S=zeros(100,50);
V=rand(100,50);
Index=round(50*rand(1,50))
for i=1:50
S(:,Index(i))=S(:,Index(i))+V(:,i);
end
Thanks

请先登录,再进行评论。

 采纳的回答

Idx1 = repmat(1:size(V,1), 1, length(Index)) ;
Idx2 = repelem(Index, 1, size(V, 1));
S = accumarray([Idx1(:), Idx2(:)], V(:), size(V)) ;

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by