3

I have for example two matrices in dimension of 1x5, and I want to reshape them to be in a symmetric 5x5 matrix after doing c = a+b operation then adding the diag(c) <- 1

let's say for example:

a <- matrix(seq(1,5), byrow = T)
b <- matrix(seq(1,5), byrow = T)

the result I'm looking for is:

1 3 4 5 6
3 1 5 6 7
4 5 1 7 8
5 6 7 1 9
6 7 8 9 1

Please help, and thank you in advance

1 Answers1

2

We can use outer to do the sum and then assign the diagonal elements to 1

out <- outer(a[,1], b[,1], FUN = `+`)
diag(out) <- 1
out
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    3    4    5    6
#[2,]    3    1    5    6    7
#[3,]    4    5    1    7    8
#[4,]    5    6    7    1    9
#[5,]    6    7    8    9    1
akrun
  • 874,273
  • 37
  • 540
  • 662