I have a matrix n*n with values along its diagonal. I would like to create a new matrix by multiplying elements of the diagonal matrix b
, corresponding to the position of the elements along the diagonal.
For example, say I have a 4*4 matrix:
set.seed(5)
b <- diag(sample(4))
colnames(b) <- rownames(b) <- c("AAA" , "BBB" , "CCC" , "DDD")
Giving matrix b
:
AAA BBB CCC DDD
AAA 2 0 0 0
BBB 0 3 0 0
CCC 0 0 1 0
DDD 0 0 0 4
I would like to compute matrix d
by multiplying as follows:
b[AAA , AAA] = 2 * 2 = 4
and
b[AAA , BBB] = 2 * 3 = 6
The end result should give:
AAA BBB CCC DDD
AAA 4 6 2 8
BBB 6 9 3 12
CCC 2 3 1 4
DDD 8 12 4 16
Is there an efficient code that can do this without having to do this by hand? This would not be possible if the matrix is very large.
CodePudding user response:
What you are describing is the outer product of the diagonal. You can get this by doing:
outer(diag(b), diag(b))
AAA BBB CCC DDD
AAA 4 6 2 8
BBB 6 9 3 12
CCC 2 3 1 4
DDD 8 12 4 16
or
diag(b) %o% diag(b)
AAA BBB CCC DDD
AAA 4 6 2 8
BBB 6 9 3 12
CCC 2 3 1 4
DDD 8 12 4 16