如何使用MATLAB中的FIND函数计算项目数?

时间:2010-06-21 14:18:18

标签: matlab count find

如何使用函数FIND来计算给定值的项数而不是使用循环?例如,在下面的数组item中,有3个出现的数字23,2次出现的数字为22,2次出现的数字为20。

....
for i=2:n
    if item(i-1)~=item(i)
        nItem21(i)=1;
    else 
        nItem21(i)=nItem21(i-1)+1;
    end
end

item Num
23   2
23   4
23   6
22   3
22   1
20   6
20   8

4 个答案:

答案 0 :(得分:4)

您可以执行以下操作:确定item的值发生更改的位置,然后使用diff来获取计数。

item = [
23   
23   
23   
22   
22   
20   
20];

% find the 'last' entries of each consecutive group of numbers
chgRowNum = [find(item(1:end-1) ~= item(2:end);length(item)]; 

counts = diff([0;chgRowNum]);

correspondingItems = item(chgRowNum);

答案 1 :(得分:2)

Find返回数组中非零元素的索引。如果您想要计算元素的所有出现次数(假设它们是整数),则可以使用hist函数。通过分配输出,它不会绘制直方图。相反,它将返回一系列事件。

x=[20 23 20 22 23 21 23 22];
bins=min(x):max(x);
count=hist(x,bins);
list=unique(x);

现在count包含出现次数,list包含每个唯一的数组元素。 要摆脱零计数元素:

idx=find(count);
count=count(idx);

或单行选项(不使用find):

count=count(count~=0);

答案 2 :(得分:2)

为了完整起见,我会使用histc函数。

item = [
23   
23   
23   
22   
22   
20   
20];
%get the unique items
[uni_items, minds, uinds] = unique(item);
%count them
counts = histc(uinds, 1:numel(uni_items));
%put them in the original order
ocounts = counts(minds);

这会照顾他们没有按顺序或者他们不是整数。

答案 3 :(得分:2)

这种情况的另一个选择是使用函数ACCUMARRAY,这不需要首先对列表进行排序。如果您在item中有一组范围为1:N且其中N为任意整数值的数字,则此功能特别有用。以下是它如何适用于您的示例:

item = [23; 23; 23; 22; 22; 20; 20];  %# A column vector of integers
counts = accumarray(item,1);          %# Collect counts of each item into
                                      %#   a 23-by-1 array

数组counts是一个23乘1的数组,其中由23,22和20索引的元素分别包含计数3,2和2。所有其他元素都是0(即没有找到数字1到19或21的计数)。

如果您想获取item中唯一值的列表及其相应的计数,可以使用UNIQUE函数执行此操作:

>> uniqueValues = unique(item)  %# Get the unique values in item

uniqueValues =

    20
    22
    23

>> counts = counts(uniqueValues)  %# Get just the counts for each unique value

counts =

     2
     2
     3