繁体   English   中英

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

[英]How can I count the number of items using the FIND function in MATLAB?

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

....
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

您可以执行以下操作:确定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);

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);

或单行选项(不使用查找):

count=count(count~=0);

为了完整histc我将使用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);

这样可以避免它们不按顺序排列或不是整数。

这种情况的另一种选择是使用功能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 x 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM