在MATLAB中找出矩阵中零元素的数量 [英] Find the number of zero elements in a matrix in MATLAB
问题描述
我有一个名为A
的NxM
矩阵.经过一些过程后,我想计算零个元素.
如何在一行代码中做到这一点?我试过A==0
返回2D矩阵.
I have a NxM
matrix for example named A
. After some processes I want to count the zero elements.
How can I do this in one line code? I tried A==0
which returns a 2D matrix.
推荐答案
有一个用于查找非零矩阵元素nnz
数量的函数.您可以在逻辑矩阵上使用此函数,该矩阵将返回true
的数量.
There is a function to find the number of nonzero matrix elements nnz
. You can use this function on a logical matrix, which will return the number of true
.
在这种情况下,我们将nnz
应用于矩阵A==0
,因此,如果原始元素为0,则逻辑矩阵的元素为true
,对于除0以外的任何其他元素,false
. >
In this case, we apply nnz
on the matrix A==0
, hence the elements of the logical matrix are true
, if the original element was 0, false
for any other element than 0.
A = [1, 3, 1;
0, 0, 2;
0, 2, 1];
nnz(A==0) %// returns 3, i.e. the number of zeros of A (the amount of true in A==0)
基准测试的功劳归Divarkar所有.
The credits for the benchmarking belong to Divarkar.
使用以下参数和输入,可以使用timeit
对这里提出的解决方案进行基准测试.
Using the following paramters and inputs, one can benchmark the solutions presented here with timeit
.
输入尺寸
- 小型数据大小-
1:10:100
- 中等大小的数据大小-
50:50:1000
- 大数据量-
500:500:4000
- Small sized datasize -
1:10:100
- Medium sized datasize -
50:50:1000
- Large sized datasize -
500:500:4000
改变零的百分比
- 〜零的10%-
A = round(rand(N)*5);
- 〜50%的零--
A = rand(N);A(A<=0.5)=0;
- 〜90%的零--
A = rand(N);A(A<=0.9)=0;
- ~10% of zeros case -
A = round(rand(N)*5);
- ~50% of zeros case -
A = rand(N);A(A<=0.5)=0;
- ~90% of zeros case -
A = rand(N);A(A<=0.9)=0;
结果如下所示-
1)小数据大小
2.中等数据大小
3.大型数据
观察
-
如果仔细查看中型和大型数据大小的
NNZ
和SUM
性能图,您会发现在10%
和90%
零情况下,它们的性能彼此接近.对于50%
零的情况,SUM
和NNZ
方法之间的性能差距相对较大.
If you look closely into the
NNZ
andSUM
performance plots for medium and large datasizes, you would notice that their performances get closer to each other for10%
and90%
zeros cases. For50%
zeros case, the performance gap betweenSUM
andNNZ
methods is comparatively wider.
作为对所有数据大小和零的所有三个分数情况的一般观察,
SUM
方法似乎是无可争议的赢家.再次,在这里观察到一个有趣的事情,一般情况下的解决方案sum(A(:)==0)
的性能似乎比sum(~A(:))
更好.
As a general observation across all datasizes and all three fraction cases of zeros,
SUM
method seems to be the undisputed winner. Again, an interesting thing was observed here that the general case solution sum(A(:)==0)
seems to be better in performance than sum(~A(:))
.
这篇关于在MATLAB中找出矩阵中零元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!