【问题标题】:To find the diagonal elements of a Matrix查找矩阵的对角线元素
【发布时间】:2016-07-07 09:27:20
【问题描述】:

我编写了一个函数来将矩阵的对角元素存储到向量中。但输出并不像我预期的那样。代码是

diagonal <- function(x) {
for( i in nrow(x)){ 
for(j in ncol(x)){
  if(i == j) { 
    a <- x[i,j]
  } 
}
}
print(a)
}

我将一个矩阵传递给函数。 代码有什么问题?

【问题讨论】:

标签: r


【解决方案1】:

我们可以使用diag函数

diag(m1)
#[1] 1 5 9

或者

m1[col(m1)==row(m1)]
#[1] 1 5 9

如果我们使用for 循环,我们将按行和列的顺序循环,即1:nrow(x)/1:ncol(x),而不是nrow(x)/ncol(x)

diagonal <- function(x) {
  a <- numeric(0)
 for( i in 1:nrow(x)){ 
  for(j in 1:ncol(x)){
     if(i == j) { 
       a <-  c(a, x[i,j])
     } 
    }
  }
 a
 }

diagonal(m1)
#[1] 1 5 9

数据

m1 <- matrix(1:9, ncol=3)

【讨论】:

  • 我知道 diag() 函数。我是 R 的初学者。所以正在练习编写函数
  • 最好预先分配和填充a,而不是糟糕的性能复制和附加——n = min(nrow(x), ncol(x)); a = numeric(n)。与其遍历不能满足条件的行/列,不如for (i in seq_len(n)) a[i] = x[i, i]
  • @MartinMorgan 你是对的。我只是展示了一种以最少干预纠正 OP 代码的方法。
  • 加一个只为m1[col(m1)==row(m1)]
猜你喜欢
  • 1970-01-01
  • 2016-06-02
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多