Counting the number of elements in a table.

60 views (last 30 days)
I have a table that is 500x4. The fourth row contains the numerical values. What I want to do is use a code to count the variables in a certain range. For example, I want to know how many values in that row are greater than or equal to 1, but less than or equal to 6. I tried the count command, but it didn't do anything. Any help would be greatly appreciated.

Accepted Answer

Image Analyst
Image Analyst on 25 Jan 2018
Try this:
% Build sample table:
m = 10 * rand(500,4);
t = table(m(:,1), m(:,2), m(:,3), m(:,4));
% Now that we have a table, we can begin.
% Extract 4th row
row4 = t{4, :} % NOTE: braces, NOT parentheses since it's a table, not a double array.
inRange = row4 >= 1 & row4 <= 6
numberInRange = sum(inRange)
  2 Comments
Peter Perkins
Peter Perkins on 25 Jan 2018
To do this on every row, try this:
>> m = 10 * rand(5,4);
>> t = array2table(m)
t =
5×4 table
m1 m2 m3 m4
______ ______ ______ ______
4.1948 3.2883 7.022 9.9833
2.9618 9.7814 1.4663 3.996
5.8959 9.5053 6.5502 8.9666
8.3438 8.1493 5.1842 6.5132
6.4523 1.6561 1.6406 8.2775
>> inRange = sum((t.Variables >= 1) & (t.Variables <= 6),2)
inRange =
2
3
1
1
2
rowfun is also a candidate here.
Prior to R2016b, you'll have to substitute t{:,:} for t.Variables.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!