how can I count up the number from a specific interval?

51 views (last 30 days)
Chiara Lanzi
Chiara Lanzi on 25 Oct 2019
Edited: ME on 26 Oct 2019
HI,I am pretty new with Mablab and I need some help.
I have created a vector d with a random function and I need to count up the number of instances where di> 8.
How can I do it?

Answers (3)

Nadir Altinbas
Nadir Altinbas on 25 Oct 2019
hello for instance interval 8 < x > 999
x = 8 : 0.5: 999;
it increases as 0.5 up to 999 example
ok
-nadir altinbas

ME
ME on 25 Oct 2019
Edited: ME on 25 Oct 2019
Assuming you want the number of elements greater than 8 rather than the sum of the elements greater than 8 then you can simply use:
numel(d(d>8))

Steven Lord
Steven Lord on 25 Oct 2019
Generate a logical mask that is true where your data is in your specific interval and false where it is not.
x = 0:10
mask = x > 8
Count the number of nonzero (non-false) values in your mask using the nnz function.
nnz(mask) % 2, corresponding to x = 9 and x = 10
You can use the logical indexing technique shown by ME if you need to extract the elements of x that are in your interval. But if you're just trying to count them, that's extra work you don't have to do.
elementsGreaterThan8 = x(mask)
  3 Comments
ME
ME on 26 Oct 2019
I agreed that your approach was faster! Yes, for the 100 elements I used (i.e. a small example) the time difference was small. I thought it went without saying that this difference would scale up as the number of elements increased but it’s great to get a better handle on these differences.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by