簡體   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