Count values in an array if the sum of the values exceeds a certain number

1 次查看(过去 30 天)
I am a beginner in MATLAB. I have an array of [0.55, 0.4, 0.55], and I would like to count the how many values should be included to exceed a certain number (0.9 for example).
x= 0.5500
0.4000
0.0500
I would like the output to be:
y= 2
Because the sum of the first two values are already greater than 0.9, there is no need to include the third number.
This is the situation of three numbers, I would also want to see how this can work for a list of more than three values.
Thanks!

回答(1 个)

aborghes
aborghes 2017-6-19
probably not the most elegant, but this seems to work:
x = [.55, .4, .05, .5, .9]
num = 0
val = .9
for y=1:length(x)
if(num<val)
num = num+x(i)
else
y = y-1;
break
end
end
y
the value of why at the end will give you the result you are looking for
  1 个评论
Xiaochen Sun
Xiaochen Sun 2017-6-19
Thanks! I finally find a way to do this...
x = [.55, .4, .05, .5, .9]
x=sort(x,'descend')
cumx=cumsum(x)
n=find(cumx>=0.9,1)
This works for me now. But thank you for your reply!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by