Perform "outer product" of 2-D matrix and return a 3-D array in MATLAB -
i operation on 2-d matrix somehow looks outer product of vector. have written codes task, pretty slow, know if there can accelerate it.
i show code wrote first, followed example illustrate task wanted do.
my code, version row-by-row
function b = outer2d(a) b = zeros(size(a,1),size(a,2),size(a,2)); %pre-allocate output array j = 1 : size(a,1) b(j,:,:) = transpose(a(j,:))*a(j,:); %perform outer product on each row of , assign j-th layer of b end end
using matrix = randn(30000,20) input testing, spends 0.317 sec.
my code, version page-by-page
function b = outer2d(a) b = zeros(size(a,1),size(a,2),size(a,2)); %pre-allocate output array j = 1 : size(a,2) b(:,:,j) = repmat(a(:,j),1,size(a,2)).*a; %evaluate b page-by-page end end
using matrix = randn(30000,20) input testing, spends 0.146 sec.
example 1
a = [3 0; 1 1; 1 0; -1 1; 0 -2]; %a input matrix. b = outer2d(a); disp(b)
then expect
(:,:,1) = 9 0 1 1 1 0 1 -1 0 0 (:,:,2) = 0 0 1 1 0 0 -1 1 0 4
the first row of b, [9 0; 0 0], outer product of [3 0], i.e. [3; 0]*[3 0] = [9 0; 0 0].
the second row of b, [1 1; 1 1], outer product of [1 1], i.e. [1; 1]*[1 1] = [1 1; 1 1].
the third row of b, [1 0; 0 0], outer product of [1 0], i.e. [1; 0]*[1 0] = [1 0; 0 0].
and same remaining rows.
example 2
a = 0 -1 -2 0 1 0 -3 0 2 0 0 0 1 0 0 b = outer2d(a) disp(b)
then, similar example 1, expected output is
(:,:,1) = 0 0 0 0 0 0 9 0 -6 0 0 0 1 0 0 (:,:,2) = 0 1 2 0 1 0 0 0 0 0 0 0 0 0 0 (:,:,3) = 0 2 4 0 0 0 -6 0 4 0 0 0 0 0 0
because real input in project in size of 30000 × 2000 , task performed many times. acceleration of task quite essential me.
i thinking of eliminating for-loop in function. may have opinions on problem?
with auto expansion:
function b = outer2d(a) b=permute(permute(a,[3 1 2]).*a',[2 3 1]); end
without auto expansion:
function b = outer2dold(a) b=permute(bsxfun(@times,permute(a,[3 1 2]),a'),[2 3 1]); end
Comments
Post a Comment