R中的左序二进制矩阵算法

Left ordered binary matrix algorithm in R

我正在尝试生成一种算法(最好是 R 中的函数)以按左侧的列对任何二进制矩阵进行排序,如下所示:

首先,重要的是要提到该函数只是对列进行排序。我们无法在不移动所有列的情况下移动特定值。任何行也移动。该函数是将二进制矩阵的列按该列表示的二进制数的大小从左到右排序得到的,取第一行作为最高位。

示例:假设我有一个矩阵 $\begin{pmatrix}1&0&0&1&0&1&0\ 1&1&0&1&0&1&0\ 0&1&1&0&1&0&0\ 0&1&1&1&1&0&1\end{pmatrix}$ 我想把它转换成 $\begin{pmatrix}1&1&1&0&0&0&0\ 1&1&1&1&0&0&0\ 0&0&0&1&1&1&0\ 1&0&0&1&1&1&1\end{p矩阵}$

事实上,我通过先取所有带 1 的列来排序第一行。 在第 2 行中,在第一行带有 1 的列之间,我先对带有 1 的列进行排序,然后在第一行带有 0 的列之间执行相同的操作。 以此类推直到最后一行。

只需要处理矩阵列的数值,并使用 order 函数适当地将列排序为 '[ , ] 中的第二个参数' 矩阵运算符。开始了:

    # vect is a binary vector
    # returns the value of the vector
    to.value <- function(vect){
       L <- length(vect)
       value <- 0
       for (i in L:1){
           value <- value + 2^(L-i)*vect[i]
      }
      return(value)
  }

  # matrix is a square binary matrix
  # returns the values of the columns in a vector

 column.values <- function(matrix){
     result <- numeric(ncol(matrix))
     for (i in 1:length(result)){
       result[i] <- to.value(matrix[,i])
    }
    return(result)
}

    # matrix is a square binary matrix
    # returns the matrix in the prescribed order

   get.ordered.matrix <- function(matrix){
      vals <- column.values(mat)
      return(matrix[,rev(order(vals))])
  }

    ### Test ###

 l <- 8
 set.seed(20)
 mat <- matrix(floor(runif(l^2,min=0,max=2)),ncol=l)
 mat
 get.ordered.matrix(mat)