Count elements of a cell array based on two conditions

2 vues (au cours des 30 derniers jours)
Maria
Maria le 27 Juil 2014
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 cases 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.
Can someone help me? Thank you.
  2 commentaires
Image Analyst
Image Analyst le 27 Juil 2014
By "case" do you mean "row"?
Maria
Maria le 27 Juil 2014
Yes

Connectez-vous pour commenter.

Réponse acceptée

Azzi Abdelmalek
Azzi Abdelmalek le 28 Juil 2014
out=nnz(cellfun(@(x,y) all([x<25,y>25]),A(2:end,3),A(2:end,5)))

Plus de réponses (2)

Geoff Hayes
Geoff Hayes le 27 Juil 2014
Maria - you can try the following
length(find(cell2mat(A(:,3))<25 & cell2mat(A(:,5))>25))
We convert the third and fifth columns of A to vectors using cell2mat and then find which indices from both vectors satisfy the two conditions. length is then used to do the the count.
  2 commentaires
Maria
Maria le 27 Juil 2014
It gives this error: Error using & Matrix dimensions must agree.
Geoff Hayes
Geoff Hayes le 27 Juil 2014
Given this error, it would seem as if the two columns, cellmat(A(:,3)) and cellmat(A(:,5)) are of different dimension. Are both these columns just like in the above matrix?
A(:,3) =
[]
[ 21]
[ 18]
[ 33]
[104]
[ 21]
[ 10]
A(:,5) =
[]
[104]
[ 60]
[ 33]
[104]
[ 21]
[ 13]
During the cell2mat conversion, the empty elements are removed. I wonder if perhaps your two columns have a different number of empty elements, [], so that after the conversion, the two columns are of a different dimension.

Connectez-vous pour commenter.


Image Analyst
Image Analyst le 27 Juil 2014
Another option to count rows meeting the criteria:
theCount = sum(cell2mat(A(:,3)) < 25 & cell2mat(A(:,5)) > 25)
  3 commentaires
Maria
Maria le 27 Juil 2014
That's what I had already tried.. :(
Image Analyst
Image Analyst le 27 Juil 2014
Here's the exact code I used and it works fine:
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}
theCount = sum(cell2mat(A(:,3)) < 25 & cell2mat(A(:,5)) > 25)
Post your adaptation of my code so I can see what you changed and see how you broke it.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by