[英]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);
為了完整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.