0

Here is my question. I'm trying to create a list with all the symmetric canonical matrix of size nxn with a diagonal of 1,..,1 and k element equal to one in each triangle.

For instance if n=3 and k=2, I want to generate all 3x3 matrix symmetric with 1,1,1 diagonal and 2 element equal to 1 up and below the diagonale:

1 1 1    
1 1 0    
1 0 1

And

1 1 0    
1 1 1    
0 1 1

And

1 1 0    
1 1 1    
0 1 1

And

1 0 1    
0 1 1    
1 1 1

Can you help me ?

Regards

1
  • You want us to write a logic for you? At least show what you have tried... Then we can think about it..
    – vrajs5
    May 27, 2014 at 8:32

1 Answer 1

0

I don't understand why you generate the second matrix twice. So the solution below just creates all unique symmetric matrices with the desired properties. If you want some of them twice, you will have to tweak the code a bit.

# load required packages
require(plyr)
# function to generate a list of "canonical matrices"
generate.canonical.matrix <- function(n, k){
  # initialize
  m <- matrix(0, nrow=n, ncol=n)
  # number of positions in the upper triangle
  K <- n*(n-1)/2
  if (K<k) stop("k cannot be larger than n*(n-1)/2")
  # upper triangle matrix
  upper <- which(upper.tri(m))
  # for all combinations of k elements
  alply(combn(K, k), 2, function(index){ # CHANGE combn(K, k) TO GET NON-UNIQUE MATRICES
    # set upper tirangle matrix 
    m[upper[index]] <- 1
    # combine upper, lower and diagonal matrices
    m+t(m)+diag(n)
  })
}
# function call
generate.canonical.matrix(3, 2)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.