找出输入是否是 R 中的 Toeplitz 矩阵
Find out if input is a Toeplitz Matrix in R
给定一个随机矩阵(任意大小!),编写一个函数来确定该矩阵是否为托普利茨矩阵。在线性代数中,托普利茨矩阵是其中从左上角到右下角的任何给定对角线上的元素相同的矩阵。
这是一个例子:
x <- structure(c(1, 5, 4, 7, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 8,
4, 3, 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
所以我们的函数应该接收这样的矩阵,如果满足条件return TRUE。
为了测试该功能,可以使用stats::toeplitz()
生成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))
}
给定一个随机矩阵(任意大小!),编写一个函数来确定该矩阵是否为托普利茨矩阵。在线性代数中,托普利茨矩阵是其中从左上角到右下角的任何给定对角线上的元素相同的矩阵。
这是一个例子:
x <- structure(c(1, 5, 4, 7, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 8,
4, 3, 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
所以我们的函数应该接收这样的矩阵,如果满足条件return TRUE。
为了测试该功能,可以使用stats::toeplitz()
生成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))
}