How to vectorize the evaluation of outer product matrix for every row of the 2D matrix? [duplicate]

白昼怎懂夜的黑 提交于 2019-12-25 00:37:35

问题


I am trying to speed the process in evaluation the outer product matrix. I have a 4*n matrix named a. I want to evaluate the outer product matrix for every row of a, by the formula:

K = a*a';

If I code this process using a for loop, it is as below:

K=zeros(4,4,size(a,2));
for i=1:size(a,2)
    K(:,:,i) = a(:,i)*a(:,i)';
end

I have found another method, using cellfun, which is even slower than before.

acell = num2cell(a, 1);
b = cellfun(@(x)(x*x'),acell,'UniformOutput',false);
K = reshape(cell2mat(b),4,4,[]);

Is there any good way to implement these process, such as vectorization?


回答1:


You can use kron to repeat the matrix n time, so no need to preallocation, then perform an element wise multiplication with a(:).', finally reshape to add a 3rd dimension.

%Dummy 2D matrix 4x3
a = [1 4 7
     2 5 8
     3 6 9
     4 7 10]
%Size of the first dimension  
n = size(a,1);
%Repeat the matrix n time
p = kron(a,ones(1,n)).*a(:).'
%Reshape to A = 4x4x3
A = reshape(p,n,n,[])

You loose the readability of the for loop method but you should increase the performance.



来源:https://stackoverflow.com/questions/57786211/how-to-vectorize-the-evaluation-of-outer-product-matrix-for-every-row-of-the-2d

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