计算给定范围内矩阵中的值的数量

Feb*_*ono 4 matlab matrix

我有矩阵

A=[2 3 4 5 6 7;
   7 6 5 4 3 2]
Run Code Online (Sandbox Code Playgroud)

我想要计算有多少元素的值大于3且小于6.

Ans*_*ari 8

flatA = A(:);
count = sum(flatA > 3 & flatA < 6);
Run Code Online (Sandbox Code Playgroud)


Rod*_*uis 7

我可以想到几个方面:

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)
Run Code Online (Sandbox Code Playgroud)

那么,让我们测试一下最快的方法.测试代码:

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

    %# method is inserted here

end
toc
Run Code Online (Sandbox Code Playgroud)

结果(最好的5次运行,全部以秒为单位):

%# ( 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
Run Code Online (Sandbox Code Playgroud)

所以这似乎count = sum(( abs(A(:)-(6+3)/2)<3/2 ));是去这里的最佳方式.

在个人方面:我没想到比较比Matlab中的算术慢 - 有没有人知道对此的解释?

另外:为什么nnz这么慢sum?我想现在我知道比较慢于算术...