Reputation: 5039
I have a vector which is normalize(i.e. the sum of its elements is 1
) and they are ordered descending(i.e. [0.5 0.4 0.09 0.01]
).
Is there a way of obtaining the indices of the first elements who's sum is just bellow a certain threshold?
For example, in my case, for a threshold of 0.6
I would obtain 1
, the index(w.r.t. to Matlab way of indexing vector elements) of 0.5
. For a threshold of 0.91
I would obtain [1 2]
, the indices of [0.5 0.4]
, and so on.
I know that I can do this with a loop through the vector but given the fact that I am using Matlab, I thought asking whether I can do this with just a single command line or max 2, thus increasing the computational speed of my code.
Upvotes: 3
Views: 318
Reputation: 38032
The cumsum
function computes the cumulative sum of a vector's elements. doing this, and then finding the index for which the threshold turns smaller than the cumulative sum will give you your answer:
V = [0.5 0.4 0.09 0.01]
t = 0.6;
index = find(t < cumsum(V), 1)-1
Note that if index = 0
, the condition does not hold even for the first element.
If you insist on getting a vector of elements that qualify, you can simply define a range with this:
indices = 1 : (find(t<cumsum(V),1)-1)
In this case, the indices
vector is empty in case the first element doesn't qualify.
Upvotes: 4