Reputation: 843
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
a[1,1]
I would multiply a[1,1]
with a[1,1]
giving 1a[1,2]
I would multiply a[1,2]
with a[2,1]
giving 8Repeating 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
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