提取大矩阵的非对角切片 [英] Extracting off-diagonal slice of large matrix

查看:17
本文介绍了提取大矩阵的非对角切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的 nxn 矩阵,想取出不同大小的非对角线切片.例如:

I've got a large nxn matrix and would like to take off-diagonal slices of varying sizes. For example:

1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6

我想要一个 R 函数,当给定矩阵和对角线切片的宽度"时,它会返回一个仅包含这些值的 nxn 矩阵.所以对于上面的矩阵,比如 3,我会得到:

I'd like an R function which, when given the matrix and "width of diagonal slice" would return an nxn matrix of just those values. So for the matrix above and, say, 3, I'd get:

1 x x x x x
1 2 x x x x
1 2 3 x x x
x 2 3 4 x x
x x 3 4 5 x
x x x 4 5 6

目前我正在使用(原谅我)一个非常慢的 for 循环:

At the moment I'm using (forgive me) a for loop which is incredibly slow:

getDiags<-function(ndiags, cormat){
  resmat=matrix(ncol=ncol(cormat),nrow=nrow(cormat))
  dimnames(resmat)<-dimnames(cormat)
  for(j in 1:ndiags){
    resmat[row(resmat) == col(resmat) + j] <- 
      cormat[row(cormat) == col(cormat) + j]
  }
  return(resmat)
}

我意识到这是解决这个问题的一种非常非 R"的方式.有没有更好的方法,可能使用 diag 或 lower.tri?

I realise that this is a very "un-R" way to go about solving this problem. Is there a better way to do it, probably using diag or lower.tri?

推荐答案

size <- 6
mat <- matrix(seq_len(size ^ 2), ncol = size)


low <- 0
high <- 3

delta <- rep(seq_len(ncol(mat)), nrow(mat)) - 
    rep(seq_len(nrow(mat)), each = ncol(mat))
#or Ben Bolker's better alternative
delta <- row(mat) - col(mat)
mat[delta < low | delta > high] <- NA
mat

这适用于我机器上的 5000 x 5000 矩阵

this works with 5000 x 5000 matrices on my machine

这篇关于提取大矩阵的非对角切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆