

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I have two matrices built from combinations

mat1 <- combn(10, 2)
mat2 <- combn(20, 3)

mat1 being a 2x45 and mat2 being a 3x1140.

What I want to produce is the possible combinations assuming you take both actions in sequence. So first 10 choose 2, followed immediately by 20 choose 3, what are all the combinations. I would like to produce a matrix which has 5 rows and 51300 columns. The first column values would be (1, 2, 1, 2, 3)

What is the most appropriate way to implement this?

share|improve this question

Interesting question. Here is a solution that makes use of a couple Kronecker products:

one1 <- matrix(1, ncol = ncol(mat1))
one2 <- matrix(1, ncol = ncol(mat2))

rbind(mat1 %x% one2, one1 %x% mat2)


rbind(one2 %x% mat1, mat2 %x% one1)

depending on which combination matrix you want to recycle first.

share|improve this answer
(+1) for using %x%. Can you briefly explain how it works? The documentation is very limited. – Nishanth Apr 30 '13 at 3:21
maybe this link will help: By making one of the two matrices a row of ones, I am effectively repeating the whole matrix, a little like what the rep function does for vectors. Using the same rep analogy again, the order of the arguments is the difference between using times or each. – flodel Apr 30 '13 at 3:51

Another possible solution using expand.grid:

idx = expand.grid((1:ncol(mat1)),(1:ncol(mat2)))

rbind(mat1[,idx[,1]], mat2[,idx[,2]])

Generalization to any number of matrices:

mat.list <- list(mat1, mat2)
idx <- expand.grid(lapply(lapply(mat.list, ncol), seq_len)), mapply(function(x, j)x[, j], mat.list, idx))
share|improve this answer

Your Answer


