How to replace for loop with vectorization?
이전 댓글 표시
Is there any way I can replace this for loop with a vectorized approach?
v = zeros(4, 3);
ii = [1 ; 2 ; 3 ; 1 ; 3 ; 4];
res = [-1 -1 1 ; -1 -1 1 ; -1 -1 1 ; 1 1 -1 ; 1 1 -1 ; -1 1 -1];
for i = 1:3
v(:,i) = accumarray(ii , res(:,i));
end
I know if res was just scalar values, I could use this:
v= accumarray(ii , res);
But is it posible to remove the loop knowing that res has more than one columns?
댓글 수: 2
Walter Roberson
2019년 10월 17일
You can repmat(ii, size(res,2),1) and use res(:)
Sai Bhargav Avula
2019년 10월 23일
repmat may not be the right way as the accumarray is used here.
채택된 답변
추가 답변 (1개)
Bruno Luong
2019년 10월 23일
[iii,jj]=ndgrid(ii,1:size(res,2));
v=accumarray([iii(:) jj(:)], res(:))
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!