简体   繁体   English

基于行和列和的 0 和 1 条件随机矩阵

[英]Conditional random matrix with 0 and 1 based on row and column sums

I am trying to build a matrix in R with 1s and 0s but the matrix should be generated only if the row sums and column sums condition are satisfied.我正在尝试在 R 中构建一个矩阵,其中包含 1 和 0,但只有在满足行和和列和条件时才应该生成矩阵。 for ex:例如:

1 0 1 1
0 1 1 0
1 1 1 1
1 0 1 0

I want to create a matrix with rowsums = c(3, 2, 4, 2) and colsums = c(3, 2, 4, 2) .我想用rowsums = c(3, 2, 4, 2)colsums = c(3, 2, 4, 2)创建一个矩阵。

There probably is a more elegant solution, but this works, doesn't take long to run, and doesn't require any package:可能有一个更优雅的解决方案,但这有效,不需要很长时间运行,并且不需要任何 package:

repeat {
  repeat {
    repeat {
      repeat {
        repeat {
          x <- sample(0:1, 4, replace = T)
          if(sum(x) == 3) {
            break
          }
        }
        repeat {
          y <- sample(0:1, 4, replace = T)
          if(sum(y) == 2) {
            break
          }
        }
        repeat {
          z <- sample(0:1, 4, replace = T)
          if(sum(z) == 4) {
            break
          }
        }
        repeat {
          u <- sample(0:1, 4, replace = T)
          if(sum(u) == 2) {
            break
          }
        }
        if(sum(x[1], y[1], z[1], u[1]) == 3) {
          break
        }
      }
      if(sum(x[2], y[2], z[2], u[2]) == 2) {
        break
      }
    }
    if(sum(x[3], y[3], z[3], u[3]) == 4) {
      break
    }
  }
  if(sum(x[4], y[4], z[4], u[4]) == 2) {
    print(matrix(c(x, y, z, u), 4, 4, byrow = T))
    break
  }
}

Approaching this as a lp problem which phiver also alludes to in the link provided by Stephane Laurent in the comment:将其视为一个 lp 问题,phiver 在 Stephane Laurent 在评论中提供的链接中也提到了这个问题:

library(lpSolve)
library(data.table)

nr <- 4
nc <- 4
ne <- nr * nr

v <- vector("integer", ne)
colvec <- replace(v, seq_along(v) <= nr, 1L)
rowvec <- replace(v, seq_along(v) %% nc == 1, 1L)

colconstr <- c(3, 2, 4, 2)
rowconstr <- c(3, 2, 4, 2)

const.mat <- do.call(rbind, c(
    data.table::shift(colvec, seq(0L, ne - nc, nc), fill=0L),
    data.table::shift(rowvec, 0L:(nr-1L), fill=0L)))
const.rhs <- c(colconstr, rowconstr)

s <- lpSolve::lp("min", runif(ne), const.mat, 
    rep("==", nrow(const.mat)), const.rhs, all.bin=TRUE)$solution
matrix(s, nrow=nr)

sample output:样品 output:

     [,1] [,2] [,3] [,4]
[1,]    1    0    1    1
[2,]    1    0    1    0
[3,]    1    1    1    1
[4,]    0    1    1    0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM