Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of values in matrix within given range

Tags:

matrix

matlab

I have matrix

A=[2 3 4 5 6 7;
   7 6 5 4 3 2]

I want to count how many number of elements have a value greater than 3 and less than 6.

like image 664
Febri Dwi Laksono Avatar asked Nov 30 '22 05:11

Febri Dwi Laksono


2 Answers

flatA = A(:);
count = sum(flatA > 3 & flatA < 6);
like image 129
Ansari Avatar answered Dec 02 '22 19:12

Ansari


I can think of a few ways:

count = numel(A( A(:)>3 & A(:)<6 ))      %# (1)

count = length(A( A(:)>3 & A(:)<6 ))     %# (2)

count = nnz( A(:)>3 & A(:)<6 )           %# (3)

count = sum( A(:)>3 & A(:)<6 )           %# (4)

Ac = A(:);
count = numel(A( Ac>3 & Ac<6 ))          %# (5,6,7,8)
%# prevents double expansion
%# similar for length(), nnz(), sum(),
%# in the same order as (1)-(4)

count = numel(A( abs(A-(6+3)/2)<3/2 ))   %# (9,10,11,12)
%# prevents double comparison and & 
%# similar for length(), nnz(), sum()
%# in the same order as (1)-(4)

So, let's test what the fastest way is. Test code:

A = randi(10, 50);
tic
for ii = 1:1e5

    %# method is inserted here

end
toc

results (best of 5 runs, all in seconds):

%# ( 1): 2.981446
%# ( 2): 3.006602
%# ( 3): 3.077083
%# ( 4): 2.619057
%# ( 5): 3.011029
%# ( 6): 2.868021
%# ( 7): 3.149641
%# ( 8): 2.457988
%# ( 9): 1.675575
%# (10): 1.675384
%# (11): 2.442607
%# (12): 1.222510

So it seems that count = sum(( abs(A(:)-(6+3)/2)<3/2 )); is the best way to go here.

On a personal note: I did not expect comparison to be slower than arithmetic in Matlab -- does anyone know an explanation for this?

Plus: why is nnz so slow compared to sum? I guess that makes sense now that I know comparison is slower than arithmetic...

like image 33
Rody Oldenhuis Avatar answered Dec 02 '22 18:12

Rody Oldenhuis