【问题标题】:Find out if input is a Toeplitz Matrix in R找出输入是否是 R 中的 Toeplitz 矩阵
【发布时间】:2021-03-17 12:07:54
【问题描述】:

给定一个随机矩阵(任意大小!),编写一个函数来确定该矩阵是否为 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

【问题讨论】:

    标签: r linear-algebra toeplitz


    【解决方案1】:

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

    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))
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-09
      • 2014-02-07
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多