Adrian
Adrian

Reputation: 843

How to multiply element row-column with element column-row in a matrix, for all elements?

I have a very large matrix and would like to multiply element [a,b] with element [b,a] and then repeat for each other element.

Say I have a matrix a:

a <- matrix(c(1:9), byrow = TRUE, nrow = 3)

that gives a matrix

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

Repeating this for every element should give:

     [,1] [,2] [,3]
[1,]    1    8   21
[2,]    8   25   48
[3,]   21   48   81

which I calculated using:

b <- matrix(c(a[1,1] * a[1,1], a[1,2] * a[2,1], a[1,3] * a[3,1],
              a[2,1] * a[1,2], a[2,2] * a[2,2], a[2,3] * a[3,2],
              a[3,1] * a[1,3], a[3,2] * a[2,3], a[3,3] * a[3,3]) , 
            byrow = TRUE, nrow = 3)

My code is extremely choppy and would be impossible to use for very large matrices. Is there any code that can do this using loops or any other easy way?

Upvotes: 1

Views: 36

Answers (1)

markus
markus

Reputation: 26343

You could multiply a with its transpose

a * t(a)
#     [,1] [,2] [,3]
#[1,]    1    8   21
#[2,]    8   25   48
#[3,]   21   48   81

Upvotes: 3

Related Questions