[英]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.