r - 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 的列之间执行相同的操作。一直到最后一行。
解决方案
只需处理矩阵列的数值,并适当地使用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)
推荐阅读
- xcode - IONIC 1 是否支持 iOS12?
- java - Liferay 最佳实践如何制作视图模型/图层以及如何使用 liferay-search-container 显示 2 个表记录
- git - 我在 Visual Studio 应用程序中更改了 2-3 行,现在版本控制说应用程序中的每个文件都是新文件?
- python - 在没有明确声明的情况下禁用 Django ModelForm 字段
- sql-server - 删除没有事件数据的行
- autohotkey - PixelSearch - 即使颜色没有以 600 x 800 显示,警报也会响起。我做错了什么?
- python - 在 Python 中查找一周的最后一个工作日
- javascript - 跨世界副本处理 Mapbox GeoJson 行?
- elasticsearch - Elasticsearch 浮点/双字段类型精度
- asp.net-core - 要求经过身份验证的用户再次键入其凭据以访问某些安全功能