Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a matrix of combinations

Tags:

I have 5 items each of which can take on the value of 1 or -1. I want to generate a matrix that consists of rows of the possible combinations. The order of the items does not matter and the order of the combinations does not matter. I know I could do this mechanically, but I thought that someone must know a shortcut to generating this matrix. I apologize if this is similar to other questions but none of the solutions I have found can be applied to this particular problem with my programming skills.

like image 749
ProbablePattern Avatar asked Oct 22 '10 02:10

ProbablePattern


People also ask

How do you generate all possible combinations of a set of numbers in Matlab?

C = combntns( v , k ) returns all possible combinations of the set of values v , given combinations of length k .


2 Answers

expand.grid(c(-1,1), c(-1,1), c(-1,1), c(-1,1), c(-1,1))
like image 191
Greg Avatar answered Sep 21 '22 15:09

Greg


To generalize Greg's answer:

N   <- 5
vec <- c(-1, 1)
lst <- lapply(numeric(N), function(x) vec)
as.matrix(expand.grid(lst))
like image 34
caracal Avatar answered Sep 20 '22 15:09

caracal