创建一个总和矩阵对角线的程序
我正在尝试创建一个程序,该程序总结了我创建的矩阵的对角线。我使用了下面的代码,但我不明白我制作的代码有什么问题。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这已经很棒!但是,正如评论中指出的那样,当您可能认为自己正在求和时,您正在尝试
sum
标量。您需要将x [i,j]
的结果添加到当然为零的起始值中。因此,首先创建diags
具有零值,然后在循环的每次迭代中添加结果。注意:为了进行比较,我们使用
`==
,用于在函数调用中分配=
,用于脚本`&lt中的分配; -
。更好地使用seq
函数,例如seq_len(nrow(x))
而不是1:nrow(x)
;乍看之下的收益率相同,但具有优势,例如nrow(x)
为零。使用
diag
函数检查。数据:
我使用的矩阵略有不同,它不是那么对称,并且具有更有区别的值。
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 ofx[i, j]
to a starting value which is of course zero. So first creatediags
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 theseq
functions such asseq_len(nrow(x))
instead of1:nrow(x)
; yields at first glance the same, but has advantages e.g. ifnrow(x)
is zero.Checking with the
diag
function.Data:
I used a slightly different matrix, that isn't so symmetric and has more distinguishable values.