向量元素的总和 [英] Sum of vector elements

查看:40
本文介绍了向量元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以避免使用 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 的索引号向量.取最大值给出最后一个这样的索引.然后剩下的就是将 x 从 1 加起来到这个元素.我希望这会有所帮助.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆