创建一个总和矩阵对角线的程序

发布于 2025-01-22 22:04:02 字数 280 浏览 4 评论 0原文

我正在尝试创建一个程序,该程序总结了我创建的矩阵的对角线。我使用了下面的代码,但我不明白我制作的代码有什么问题。

a <- c(1, 2, 3) 
b <- c(3, 5, 6)

x <- matrix(a, b, nrow=3, ncol=3)
x

for (i in 1:nrow(x)) {
  for (j in 1:ncol(x)) {
    if (i=j) {
      diags[i, j] <- sum(x[i, j])
    }
  }
}

I'm trying to create a program that sums the diagonal of a matrix that I've created. I used the code below but I don't understand whats wrong with the code I made.

a <- c(1, 2, 3) 
b <- c(3, 5, 6)

x <- matrix(a, b, nrow=3, ncol=3)
x

for (i in 1:nrow(x)) {
  for (j in 1:ncol(x)) {
    if (i=j) {
      diags[i, j] <- sum(x[i, j])
    }
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

肩上的翅膀 2025-01-29 22:04:02

这已经很棒!但是,正如评论中指出的那样,当您可能认为自己正在求和时,您正在尝试sum标量。您需要将x [i,j]的结果添加到当然为零的起始值中。因此,首先创建diags具有零值,然后在循环的每次迭代中添加结果。

注意:为了进行比较,我们使用`==,用于在函数调用中分配=,用于脚本`&lt中的分配; -。更好地使用seq函数,例如seq_len(nrow(x))而不是1:nrow(x);乍看之下的收益率相同,但具有优势,例如nrow(x)为零。

diags <- 0

for (i in seq_len(nrow(x))) {
  for (j in seq_len(ncol(x))) {
    if (i == j) {
      diags <- diags + x[i, j]
    }
  }
}
diags
# [1] 9

使用diag函数检查。

sum(diag(x))
# [1] 9

数据:

我使用的矩阵略有不同,它不是那么对称,并且具有更有区别的值。

x <- matrix(1:9 , nrow=4, ncol=3)

It's already great code! However, as was noted in comments, you were trying to sum a scalar when you probably thought you were summing a vector. You need to add the result of x[i, j] to a starting value which is of course zero. So first create diags with value zero and add the result to it in each iteration of the loop.

Notes: for comparisons we use `==`, for assignment in function calls =, and for assignment in the script `<-`. Better use the seq functions such as seq_len(nrow(x)) instead of 1:nrow(x); yields at first glance the same, but has advantages e.g. if nrow(x) is zero.

diags <- 0

for (i in seq_len(nrow(x))) {
  for (j in seq_len(ncol(x))) {
    if (i == j) {
      diags <- diags + x[i, j]
    }
  }
}
diags
# [1] 9

Checking with the diag function.

sum(diag(x))
# [1] 9

Data:

I used a slightly different matrix, that isn't so symmetric and has more distinguishable values.

x <- matrix(1:9 , nrow=4, ncol=3)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文