user3557054
user3557054

Reputation: 219

Count elements of a cell array based on two conditions in Matlab

I have the following cell array:

A={'x' 2000 []  2001    []
26  61      21  157     104
41  98      18  76      60
125 20  33  20  33
143 157 104 157 104
172 61  21  61  21
177 559 10  559 13}

I would like to count only the rows in which A(:,3)<25 and A(:,5)>25, so I would get as output:

Output={2}

I tried this:

sum(cell2mat(A(:,3))<25 & cell2mat(A(:,5))>25)

but to use & inputs must have the same size.

Upvotes: 2

Views: 401

Answers (1)

rayryeng
rayryeng

Reputation: 104565

Your syntax is right. I don't get why you are getting an error. Let's break up each portion of your statement down into individual statements:

b1 = cell2mat(A(:,3)) < 25

b1 =

 1
 1
 0
 0
 1
 1

b2 = cell2mat(A(:,5)) > 25

b2 =

 1
 1
 1
 1
 0
 0

c = b1 & b2

c =

 1
 1
 0
 0
 0
 0

a = sum(c)

a = 2

The answer should be 2, which is correct. When converting each column using cell2mat, the first row is ignored as its empty and so you get a column of 6 elements instead of 7. As such, this will automatically start from the second row and onward. The only two rows that satisfy the above condition where the third row is less than 25 and the fifth row is greater than 25 are the first and second valid numbers in both columns. By the way, the output in your post should be both 2 and 3.

I've answered your series of questions before, so the first row consists of titles if I'm not mistaken. As such, to ensure that things are consistent, make sure you access entries from the second row and onward from each of the columns. This ensures that you are not looking at the titles and you want to look at numerical data instead. In other words, to be safe, do this:

a = sum(cell2mat(A(2:end,3)) < 25 & cell2mat(A(2:end,5)) > 25);

In any case, if you want to get the valid rows that the above condition satisfies, use find then offset by 1 to skip the first row as we want to ignore the titles for both columns in the original cell array. In other words:

ind = find(cell2mat(A(2:end,3)) < 25 & cell2mat(A(2:end,5)) > 25) + 1

ind = 

2
3

Upvotes: 2

Related Questions