Matlab: Argmax and dot product for each row in a matrix

时光总嘲笑我的痴心妄想 提交于 2019-12-04 04:10:13

问题


I have 2 matrices = X in R^(n*m) and W in R^(k*m) where k<<n. Let x_i be the i-th row of X and w_j be the j-th row of W. I need to find, for each x_i what is the j that maximizes <w_j,x_i>

I can't see a way around iterating over all the rows in X, but it there a way to find the maximum dot product without iterating every time over all of W?

A naive implementation would be:

n = 100;
m = 50;
k = 10;
X = rand(n,m);
W = rand(k,m);
Y = zeros(n, 1);

for i = 1 : n
  max_ind = 1;
  max_val = dot(W(1,:), X(i,:));
  for j = 2 : k
       cur_val = dot(W(j,:),X(i,:));

       if cur_val > max_val
          max_val = cur_val;
          max_ind = j;
       end

   end

   Y(i,:) = max_ind;
end

回答1:


Dot product is essentially matrix multiplication:

[~, Y] = max(W*X');



回答2:


bsxfun based approach to speed-up things for you -

[~,Y] = max(sum(bsxfun(@times,X,permute(W,[3 2 1])),2),[],3)

On my system, using your dataset I am getting a 100x+ speedup with this.


One can think of two more "closeby" approaches, but they don't seem to give any huge improvement over the earlier one -

[~,Y] = max(squeeze(sum(bsxfun(@times,X,permute(W,[3 2 1])),2)),[],2)

and

[~,Y] = max(squeeze(sum(bsxfun(@times,X',permute(W,[2 3 1]))))')


来源:https://stackoverflow.com/questions/24570982/matlab-argmax-and-dot-product-for-each-row-in-a-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!