如何在两个向量中求和而不覆盖结果。

huangapple go评论61阅读模式
英文:

How to sum up in two vector without overriding the results

问题

我想要将两个向量求和,方式如下:

A = seq(10, 30, 10)
B = seq(1, 6, 1)
C = c()

for (i in B) {
for (j in A)
C = c(j + i)
}

C将是一个包含以下所有结果的向量:

for (i in B) {
for (j in A)
print(j + i)
}

我对矩阵不感兴趣。我可能该怎么做呢?谢谢。

英文:

I would like to sum up two vectors, in a way that:

A = seq(10, 30, 10)
B = seq(1, 6, 1)
C = c()

for (i in B) {
  for (j in A)
  C = c(j + i)
}

C would be a vector with all results appearing from:

for (i in B) {
  for (j in A)
  print(j + i)
}

I am not interested in a matrix for this. What could I possibly do?
Thanks

答案1

得分: 1

You can use outer in this case.

c(outer(A, B, `+`))
[1] 11 21 31 12 22 32 13 23 33 14 24 34 15 25 35 16 26 36

If you really need a for loop, we can use the approach provided by @Feel free in the comment:

for (i in B) {
  for (j in A)
    C = append(C, j + i)
}

C
[1] 11 21 31 12 22 32 13 23 33 14 24 34 15 25 35 16 26 36
英文:

You can use outer in this case.

c(outer(A, B, `+`))
[1] 11 21 31 12 22 32 13 23 33 14 24 34 15 25 35 16 26 36

<hr>

If you really need a for loop, we can use the approach provided by @Feel free in the comment:

for (i in B) {
  for (j in A)
    C = append(C, j + i)
}

C
[1] 11 21 31 12 22 32 13 23 33 14 24 34 15 25 35 16 26 36

huangapple
  • 本文由 发表于 2023年5月25日 22:26:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333385.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定