usumdelphini
usumdelphini

Reputation: 213

Outer product of two rectangular matrices in matlab

If I have a vector r , I can easily calculate its inner product

r=[1 2 3];
inner = r*r'
inner = 14

Same goes for the outer product

outer=r'*r

outer =

 1     2     3
 2     4     6
 3     6     9

Outer, as it should be, has NxN components (where N is the total number of components, here 3). Inner, on the other hand has m x m components (where m is the number of rows, here 1). I want to be able to do this standard operation to rectangular matrices too. The inner product of rectangular matrices is easy enough:

 r =

 1     2     3
 1     1     1
 
inner=r*r'

inner =

  14    6
  6     3

Inner has components (2x2=4) and this is what I expect from the matrix multiplication of r with its transpose. Clearly, though, it is not clear how I should calculate the outer product of with itself, because now the definition of "inner product with transpose" and "outer product with itself" have the same syntax in MATLAB. Indeed, if I try to repeat what I have done for the vector r, I obtain:

outer=r'*r

outer =

 2     3     4
 3     5     7
 4     7    10

Which is not the outer product of r with itself, as it's evident from the fact that it does not have NxN=36, but only nxn=9 components (where n is the number of column). What MATLAB has interpreted my calculation to be is the inner product of r transpose and r. How do I obtain the proper outer product, whose components are all the combinations of products between components of r?

Upvotes: 1

Views: 3173

Answers (2)

yar
yar

Reputation: 1905

The * operator in MATLAB calculates the matrix multiplication.

I guess what you want is the Kronecker product. It can be done with the kron function in MATLAB.

Upvotes: 4

Cris Luengo
Cris Luengo

Reputation: 60444

If you are looking for a 6x6 matrix, you likely want to do

r(:) * r(:).'

r(:) is a vector with all the elements of matrix r.

If you are looking for the tensor outer product of r with itself, which will have a size of 2x3x2x3, then you need to do as follows:

r .* shiftdim(r,-2)

(with the 2 being the number of dimensions in r, and the .* the element-wise multiplication with implicit singleton expansion.)

Note that both answers produce the same set of values, as does the kron(r,r) solution by yar, but all three put the resulting elements in a different order.

Upvotes: 0

Related Questions