生成二元矩阵的所有可能的排列(Generate all possible permutations of a binary matrix)
我期望生成所有可能的4x4矩阵,其中每个元素可以是0或1。
R中有这样一个功能吗?
I'm looking to generate all possible 4x4 matrices, where each element can either be a 0 or a 1.
Is there a function in R to do this?
最满意答案
这是一个函数,可以为0到2^16-1索引创建这样的矩阵:
num2mat = function(num){ matrix(as.integer(intToBits(num)),4,4) }这是它产生的结果:
> num2mat(0) [,1] [,2] [,3] [,4] [1,] 0 0 0 0 [2,] 0 0 0 0 [3,] 0 0 0 0 [4,] 0 0 0 0 > num2mat(2^15+2^13+2^10+2^8+2^7+2^5+2^2+1) [,1] [,2] [,3] [,4] [1,] 1 0 1 0 [2,] 0 1 0 1 [3,] 1 0 1 0 [4,] 0 1 0 1 > num2mat(2^16-1) [,1] [,2] [,3] [,4] [1,] 1 1 1 1 [2,] 1 1 1 1 [3,] 1 1 1 1 [4,] 1 1 1 1Here is a function that would create such matrices for indices from 0 to 2^16-1:
num2mat = function(num){ matrix(as.integer(intToBits(num)),4,4) }Here is what it produces:
> num2mat(0) [,1] [,2] [,3] [,4] [1,] 0 0 0 0 [2,] 0 0 0 0 [3,] 0 0 0 0 [4,] 0 0 0 0 > num2mat(2^15+2^13+2^10+2^8+2^7+2^5+2^2+1) [,1] [,2] [,3] [,4] [1,] 1 0 1 0 [2,] 0 1 0 1 [3,] 1 0 1 0 [4,] 0 1 0 1 > num2mat(2^16-1) [,1] [,2] [,3] [,4] [1,] 1 1 1 1 [2,] 1 1 1 1 [3,] 1 1 1 1 [4,] 1 1 1 1更多推荐
发布评论