如何解决找出输入是否是 R 中的 Toeplitz 矩阵
给定一个随机矩阵(任何大小!),编写一个函数来确定该矩阵是否为 Toeplitz 矩阵。在线性代数中,托普利兹矩阵是这样一种矩阵,其中从左上角到右下角的任何给定对角线上的元素都相同。
这是一个例子:
x <- structure(c(1,5,4,7,2,1,3,8,2),.Dim = 4:5)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 8
[2,] 5 1 2 3 4
[3,] 4 5 1 2 3
[4,] 7 4 5 1 2
所以我们的函数应该接收这样的矩阵并在满足条件时返回TRUE。
要测试该函数,可以使用 stats::toeplitz()
生成托普利兹矩阵。例如,我们函数的预期输出应该是:
> toeplitz_detector(stats::toeplitz(sample(5,5)))
> [1] TRUE
解决方法
我通过定义以下函数解决了这个问题:
toeplitz_solver <- function(a) {
# re-order a backwards,because we need to check diagonals from top-left
# to bottom right. if we don't reorder,we'll end up with top-right to
# bottom-left.
a <- a[,ncol(a):1]
# get all i and j (coordinates for every element)
i <- 1:nrow(a)
j <- 1:ncol(a)
# get all combinations of i and j
diags <- expand.grid(i,j)
# the coordinates for the diagonals are the ones where
# the sum is the same,e.g.: (3,2),(4,1),(2,3),(1,4)
sums <- apply(diags,1,sum)
indexes <- lapply(unique(sums),function(x) {
diags[which(sums == x),]
})
# indexes is now a list where every element is a list of coordinates
# the first element is a list for every coordinates for the first diag
# so on and so forth
results <- sapply(indexes,function(x) {
y <- a[as.matrix(x)]
return(all(y == y[1]))
})
# if every diagonal meets the condition,it is safe to assume that the
# input matrix is in fact toeplitz.
return(all(results))
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。