如何在MATLAB中计算数组的特定值?

时间:2018-09-01 15:35:18

标签: arrays matlab

这是一个10x10的数组arr

arr有100个元素。而且它的分布范围是-10到10,并且有5个0值。

我这样做是因为我想知道数字0。

count = 0;

for i = 1: 10
     for j = 1: 10
         if (arr (i, j) == 0)
             count = count +1;
         end
     end
end

从逻辑上讲,count在MATLAB的工作空间中应为5。 ij是10。

但是,当我运行代码时,count为0。

此代码无法计算数字。

我如何计算数字?

2 个答案:

答案 0 :(得分:2)

您可以只使用nnz来获取逻辑数组中非零元素的数量,因此arr中值为0的元素数量为

count = nnz( arr == 0 );

请阅读Why is 24.0000 not equal to 24.0000 in MATLAB?,以获取有关浮点数比较的信息,您可能需要这样做

tol = 1e-6; % some tolerance on your comparison
count = nnz( abs(arr) < tol ); % abs(arr - x) for values equal to x within +/-tol

答案 1 :(得分:1)

如果我错了,请纠正我,但听起来像您想要向量中数字出现的次数,如果是这种情况,这是一种替代方法:

arr=[1 2 2;3 3 3;5 0 0;0 0 0]; % example array where 1,2,3 occur 1x,2x,3x and 5=>1x, 0=>5x
[x(:,2),x(:,1)]=hist(arr(:),unique(arr(:))); 

将排序后的类别输出为第一列,出现次数为第二列:

x =

     0     5
     1     1
     2     2
     3     3
     5     1
相关问题