I have a sorted (Ascending trend) array as
[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]
I want to check and print the number of the repeated numbers between each "natural numbers".
for example:
between 1 and 2: 0 (no repeated)
between 2 and 3: 3 repeated with 2.4
between 3 and 4: 0
between 4 and 5: 2 repeated with 4.3
between 5 and 6: 0
between 6 and 7: 0
Is there any function in MATLAB to do this task?
you can use tabulate
, and the array need not be even sorted for that. Then just select the proper elements using logical conditions. For example:
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
the alternative is to use histc
. So if your vector is stored in a then
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)]
Then you can work with the result matrix by checking if there are any numbers between natural numbers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.