count number of values greater than threshold.
70 views (last 30 days)
Show older comments
I have time as x axis and values as y axis. I want to count no. of values greater than 30 for x axis between 1 and 60 and then between 61 & 100. count between 1 & 60 ,between 61 & 100 should be stored separately.
1 Comment
James Tursa
on 28 Oct 2016
Do you mean for x indexes between 1 and 60 (i.e. x(1:60)), or do you mean for x values between 1 and 60 (i.e. x>=1 & x <=60)?
Answers (2)
James Tursa
on 28 Oct 2016
Edited: James Tursa
on 28 Oct 2016
From your description:
x = your x-axis values
y = your y-axis values (same size as x)
threshold = 30;
g = x>=1 & x <=60;
count1 = sum(y(g) > threshold);
g = x>=61 & x <=100;
count2 = sum(y(g) > threshold);
or to mash it all together:
count1 = sum(x>= 1 & x <= 60 & y > threshold);
count2 = sum(x>=61 & x <=100 & y > threshold);
3 Comments
Image Analyst
on 29 Oct 2016
What do you mean by "count the values of y"? James showed you how to count the NUMBER of y values. Do you want to SUM the y values themselves (instead of count them)? If so, just get the indexes and use sum():
indexRange1 = x>= 1 & x <= 60 & y > threshold;
sum1 = sum(y(indexRange1));
indexRange2 = x>=61 & x <=100 & y > threshold;
sum2 = sum(y(indexRange2));
dpb
on 29 Oct 2016
Yeah, but those rely on logical tests and are difficult to generalize; either of the solutions I provided automagically handle whatever number of element groups there and the length of the y vector...
dpb
on 28 Oct 2016
Edited: dpb
on 29 Oct 2016
n=sum(reshape(y,60,[])>30).';
presuming mod(length(y),60)==0
If there are an indivisible number of elements, then
n=sum(reshape([y zeros(1,20)],60,[])>30).'; % augment y to multiple of 60
Or, if you don't like the reliance on memory storage order...
>> y=randi(50,100,1); % some sample data
>> N=60; % a number over which to group
>> subs=fix([1:length(y)].'/N-eps)+1; % indexing subscript for groups of N
>> subs(N-1:N+1) % show we got the breakpoint desired...
ans =
1 1 2
>> accumarray(subs,y,[],@(x) sum(x>30)) % the compute engine
ans =
19
14
>> sum(y(1:N)>30) % check got right answer for first grouping...
ans =
19
>>
NB: The subs vector must be column vector, note the .' transpose operator. Also note the -eps compensation on the calculation of the index; this is needed to ensure the roundoff is down for the evenly-divisible element(s) in the array, else't it'd count 1:N-1 into the first group instead 1:N.
ADDENDUM
Just to show the first solution works...
>> n=sum(reshape([y.' zeros(1,20)],60,[])>30).'
n =
19
14
>>
And, it can be generalized, too...
>> n=sum(reshape([y.' zeros(1, N-mod(length(y),N))],N,[])>30).'
n =
19
14
>>
to automate the augmentation process based on y,N
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!