Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.matlab

Topic: Counting problem
Replies: 4   Last Post: Feb 7, 2013 3:46 PM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Steven Lord

Posts: 17,944
Registered: 12/7/04
Re: Counting problem
Posted: Feb 7, 2013 9:54 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply



"Jos (10584) " <#10584@fileexchange.com> wrote in message
news:kf040a$35i$1@newscl01ah.mathworks.com...
> "Erasmus" wrote in message <keuijo$cvu$1@newscl01ah.mathworks.com>...
>> hello everyone, I want count how many times of number meet the specific
>> criteria.
>> for example, I have two matrix, A and B, I want to count the how many
>> times of element meet two criteria,1) the element in A is less than 1; 2)
>> the corresponding element(in the same location) in B is larger than 50,.
>>
>> for example
>>
>> A= [ 0.1 0.2 0.5
>> 0.9 1.3 1.2 0.7 1.2 1.5]
>> B=[2 34 43
>> 54 55 56
>> 62 43 45]
>>
>> so meet the times meeting these two criteria is 2 times, location[3,1]
>> and [2,1]
>>
>> Does anyone can help me? thank you very much!

>
> Create logical matrices using your criteria, like tfA = A < 1
> tfB = B > 50
> tfAB = tfA & tfB
> N = sum(tfAB(:))
>
> The colon is needed to sum over all elements. All this can be combined in
> a single line, which is, however, more difficult to understand.
>
> N = sum(A(:)< 1 & B(:)>50)


There's no need for SUM here since you're just looking for a count of the
nonzeros.

tfA = A < 1
tfB = B > 50
tfAB = tfA & tfB
N = nnz(tfAB)

This leads to the one-liner:

N = nnz( (A < 1) & (B > 50) );

The only part of that statement that IMO may be difficult to understand is
the NNZ function, which not a lot of people tend to use or perhaps know
about. [NNZ: it's not just for sparse matrices anymore! ;]

--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com




Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.