向量元素之和 [英] Sum of vector elements
本文介绍了向量元素之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以避免使用 do 和 while 循环来计算向量的元素之和,直到出现最后一个正元素或最后一个负元素.
Is it possible to avoid using do and while loops to calculate the sum of the elements of a vector until the appearance of the last positive element or the last negative element.
推荐答案
试试以下:
x <- 5:-5
# sum until last positive:
sum(x[1:max(which(x > 0))])
x <- -5:5
# sum until last negative:
sum(x[1:max(which(x < 0))])
解释:
Which(x > 0)
给出一个索引号向量,其中 x 大于 0.取 this 的最大值给出最后一个这样的索引.然后剩下的就是从 1 到这个元素的 x 相加.我希望这会有所帮助.
Which(x > 0)
gives a vector of index numbers at which x is greater than 0. Taking the max of this gives the last such index. Then all that remains is summing up x from 1 up to this element. I hope this helps.
这篇关于向量元素之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文