I am trying to create random binary square matrices. However, there are some constraints. I would like the diagonal to = 0. Also, the upper and lower triangles need to be inverse transpositions of each other.
To be clear, what I am looking for would look the below for a random example 5 x 5 matrix. If you look at any row/column pair e.g. 3&5, 1&4, the upper and lower triangles for those pairs have opposite results.
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 0 1 0
[2,] 1 0 0 0 0
[3,] 1 1 0 1 0
[4,] 0 1 0 0 1
[5,] 1 1 1 0 0
I am running into some problems in making my random matrices asymmetric.
Here's what I have thus far for creating a random binary 12x12 matrix:
function1 <- function(m, n) {
matrix(sample(0:1, m * n, replace = TRUE), m, n)
}
A<-function1(12,12)
A #check the matrix
diag(A)<-0
My attempt at putting the transposed upper triangle into the lower triangle:
A[lower.tri(A)] <- t(A[upper.tri(A)])
A #rechecking the matrix - doesn't seem to do it.
I have tried some variations to see if I got my upper/lower triangles mixed up, but none seem to work.
Hope this question is understandable.
fun <- function(n){
vals <- sample(0:1, n*(n-1)/2, rep = T)
mat <- matrix(0, n, n)
mat[upper.tri(mat)] <- vals
mat[lower.tri(mat)] <- 1 - t(mat)[lower.tri(mat)]
mat
}
And testing it out...
> fun(5)
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 1 0 1
[2,] 1 0 1 0 1
[3,] 0 0 0 0 0
[4,] 1 1 1 0 1
[5,] 0 0 1 0 0
> out <- fun(5)
> out + t(out)
[,1] [,2] [,3] [,4] [,5]
[1,] 0 1 1 1 1
[2,] 1 0 1 1 1
[3,] 1 1 0 1 1
[4,] 1 1 1 0 1
[5,] 1 1 1 1 0