![](/img/trans.png)
[英]Algorithm to scan an array of numbers, and count how many are between a range (0 - 24)(25 - 49) etc
[英]How count the number of repeated numbers between a range of natural numbers in an array
我有一個排序(升序)數組
[1 1 1 1 1 1.2 1.6 2 2 2 2.4 2.4 2.4 2.6 3 3.5 3.6 3.8 3.9 4 4.3 4.3 4.6 5 5.02 6 7]
我想檢查並打印每個“自然數”之間的重復數。
例如:
在1和2之間:0(不重復)
在2和3之間:3重復2.4
3至4之間:0
在4到5之間:以4.3重復2
5至6之間:0
6至7之間:0
MATLAB中有任何函數可以執行此任務?
您可以使用tabulate
,甚至不需要為此對數組進行排序。 然后只需使用邏輯條件選擇適當的元素。 例如:
A=[1 1 1 1 1 1.2 1.6 2 2 2 2.4 2.4 2.4 2.6 3 3.5 3.6 3.8 3.9 4 4.3 4.3 4.6 5 5.02 6 7]
M=tabulate(A) % get frequency table
id1=mod(M(:,1),1)>0; % get indices for non integer values
id2=M(:,2)>1; % get indices for more than one occurrence
idx=id1 & id2; % get indices that combines the two above
ans=[M(idx,1) , M(idx,2)] % show value , # of repeats
ans =
2.4000 3.0000
4.3000 2.0000
另一種方法是使用histc
。 因此,如果您的向量存儲在
h = histc(a,a); % count how many times the number is there, the a should be sorted
natNumbers = (mod(a,1)==0) .* h;
nonnatNum = (mod(a,1)>0).*h;
indNN = find(natNumbers>0);
indNNN = find(nonNatNumbers>1);
resultIndex = sort([indNN indNNN]);
result = [a(resultIndex);h(resultIndex)]
然后,您可以通過檢查自然數之間是否存在任何數來使用結果矩陣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.