-2

给定一个随机矩阵(任意大小!),编写一个函数来确定该矩阵是否为 Toeplitz 矩阵。在线性代数中,托普利茨矩阵是这样一种矩阵,其中从左上角到右下角的任何给定对角线上的元素都是相同的。

这是一个例子:

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

所以我们的函数应该接收这样的矩阵并在满足条件时返回 TRUE。

要测试该功能,可以使用stats::toeplitz()生成托普利兹矩阵。例如,我们函数的预期输出应该是:

> toeplitz_detector(stats::toeplitz(sample(5, 5)))
> [1] TRUE
4

1 回答 1

0

我通过定义以下函数解决了这个问题:

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))
}
于 2021-03-22T14:53:25.477 回答