MATLAB Answers

How to replace for loop with vectorization?

4 ビュー (過去 30 日間)
Hadi Ghahremannezhad
Hadi Ghahremannezhad 2019 年 10 月 17 日
回答済み: Bruno Luong 2019 年 10 月 23 日
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
Walter Roberson 2019 年 10 月 17 日
You can repmat(ii, size(res,2),1) and use res(:)
Sai Bhargav Avula
Sai Bhargav Avula 2019 年 10 月 23 日
repmat may not be the right way as the accumarray is used here.

サインイン to comment.

採用された回答

Sai Bhargav Avula
Sai Bhargav Avula 2019 年 10 月 23 日
Hi,
You can eliminate the for loop by using the code below.
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];
[x, y] = ndgrid(ii,1:size(res,2));
v=accumarray([x(:) y(:)],res(:));
But I would recommend to use the for loop if the size of the matrix is small.
In the above case
The elapsed time in the case of for loop is 0.000248 sec. Where as in the case of where for loop is eliminated the elapsed time is 0.000750 sec.
Hope this helps!

  0 件のコメント

サインイン to comment.

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2019 年 10 月 23 日
[iii,jj]=ndgrid(ii,1:size(res,2));
v=accumarray([iii(:) jj(:)], res(:))

  0 件のコメント

サインイン to comment.

サインイン してこの質問に回答します。


Translated by