mercredi 12 janvier 2022

Randomize non-diagonal elements of symmetric matrix

I have a symmetric matrix that I want to randomly shuffle while keeping the diagonal elements unchanged. The rows all sum to 1 and should still sum to 1 after shuffling.

Toy example below:

A <- rbind(c(0.6,0.1,0.3),c(0.1,0.6,0.3),c(0.1,0.3,0.6))
A
#      [,1] [,2] [,3]
# [1,]  0.6  0.1  0.3
# [2,]  0.1  0.6  0.3
# [3,]  0.1  0.3  0.6

I would like a matrix B with the same diagonal elements as A and still symmetric, but with the elements randomly shuffled to generate something like

B <- rbind(c(0.6,0.3,0.1), c(0.3,0.6,0.1), c(0.3,0.1,0.6))
B
#      [,1] [,2] [,3]
# [1,]  0.6  0.3  0.1
# [2,]  0.3  0.6  0.1
# [3,]  0.3  0.1  0.6

My aim is to do that on a 24 *24 matrix, so the code can be messy and no need to have something with a low computational cost. So far, I have tried with a loop but the code quickly gets excessively complicated and I was wondering whether there was a more straightforward way to do it.




Aucun commentaire:

Enregistrer un commentaire