首页 > 解决方案 > R中的左序二进制矩阵算法

问题描述

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

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

Example : Suppose I have a matrix as $\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}$ and I want to transform it in $\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{矩阵}$

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

标签: ralgorithmbinary-data

解决方案


只需处理矩阵列的数值,并适当地使用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)

推荐阅读