2
votes

I have genearalised the outer product between a 3vector and itself to take input from a collection (NxNx3 matrix) of 3-vectors.

At the moment, my function does what I want (see example output and input below), and it looks like this. I would like to make it faster by avoiding the two for loops which I currently use.

function [rr]=OuterVec(r)

N = size(r,1);
rr = zeros(N,N,3,3);

for i=1:N
    for j=1:N
        rr(i,j,:,:)=kron(reshape(r(i,j,:),[1,3]),permute(r(i,j,:),[3 2 1]));
    end
end
end

I/O Examples

c = ones(2,2);
V(1,1,:)=[1 2 3];
u = c.*V;

OuterVec(u)

ans(:,:,1,1) =

 1     1
 1     1

ans(:,:,2,1) =

 2     2
 2     2

ans(:,:,3,1) =

 3     3
 3     3

ans(:,:,1,2) =

 2     2
 2     2

ans(:,:,2,2) =

 4     4
 4     4

ans(:,:,3,2) =

 6     6
 6     6

ans(:,:,1,3) =

 3     3
 3     3

ans(:,:,2,3) =

 6     6
 6     6

ans(:,:,3,3) =

 9     9
 9     9
1

1 Answers

1
votes

You only need to permute dimensions and apply element-wise product with singleton expansion:

rr = bsxfun(@times, r, permute(r, [1 2 4 3]));

Or, in Matlab R2016b onwards,

rr = r .* permute(r, [1 2 4 3]);