问题描述
我有矩阵
A=[2 3 4 5 6 7;
7 6 5 4 3 2]
我想计算多少个元素的值大于3且小于6.
I want to count how many number of elements have a value greater than 3 and less than 6.
推荐答案
我可以想到几种方法:
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
结果(最好的5次运行,都在几秒钟之内):
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
因此,看来count = sum(( abs(A(:)-(6+3)/2)<3/2 ));
是前往此处的最佳方法.
So it seems that count = sum(( abs(A(:)-(6+3)/2)<3/2 ));
is the best way to go here.
就个人而言:我没想到比较会比Matlab中的算术慢-有人知道对此的解释吗?
On a personal note: I did not expect comparison to be slower than arithmetic in Matlab -- does anyone know an explanation for this?
Plus:为什么nnz
与sum
相比这么慢?我想现在我知道比较比算术要慢,所以这很有道理.
Plus: why is nnz
so slow compared to sum
? I guess that makes sense now that I know comparison is slower than arithmetic...
这篇关于计算给定范围内的矩阵中的值数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!