user5933603
user5933603

Reputation: 21

Multiply each element of a column with other elements of the same column

If A is the matrix i have and i wanted to get the matrix B by multiplying each element of a column with each other element of the column (one by one). And store the result in a separate matrix. So if A is 3x3 matrix will give rise to B that is 9x3 matrix.

I have used the following loop code but it just gives the result of the final iteration.

for j = [1:3]
    for i=1:3 
       B(:,j)= A(i,j) .* A(:,j);
    end
end

Could you please suggest how I can do it. Thanks

 A= 1 3 7
    2 4 8
    3 5 9

B=  1 9 49
    2 12 56
    3 15 63
    2 12 56
    4 16 64
    6 20 72
    3 15 63
    6 20 72
    9 25 81

Upvotes: 0

Views: 108

Answers (1)

Shai
Shai

Reputation: 114816

What you are looking for is the "outer product". For a column vector v with n elements, the outer product is of size n-by-n:

o = v*v'

where o(ii,jj) is the product of v(ii)*v(jj).

To do it for all columns of a matrix, you can use :

o = reshape(bsxfun(@times,permute(A,[1 3 2]),permute(A,[3, 1, 2])),[],size(A,2))

For an example input matrix A = [1 3 7;2 4 8; 3 5 9] the output o is:

 1     9    49
 2    12    56
 3    15    63
 2    12    56
 4    16    64
 6    20    72
 3    15    63
 6    20    72
 9    25    81

Upvotes: 2

Related Questions