Determining how many identical values?

조회 수: 1 (최근 30일)
Jonathan Wong
Jonathan Wong 2015년 4월 26일
답변: Image Analyst 2015년 4월 26일
Let's say that I have an array of size n and each value in the array is a randomly generated value from 1 to 100. I'll use randi for this.
randi(100,n,1)
For example, lets says the array were a size 7 and the generated matrix was [30 17 94 28 28 19 19]. I want a method that can output a value of 4 since there area total of 4 values that are identical to another within the array. What is a simple though not necessarily the most efficient way of determining how the number of values that are identical?

채택된 답변

Image Analyst
Image Analyst 2015년 4월 26일
They've been making lots of changes to the histogram routines over the last couple of versions, which makes it harder/longer for us to give answers to questions like yours. Assuming you have a recent version, you can use histcounts() and sum the bins that have counts of 2 or more:
n = 7
r = randi(100,n,1)
% Test case
r = [30 17 94 28 28 19 19]
[counts, edges] = histcounts(r, min(r):max(r)) % a new function!
binsOfDuplicates = counts >= 2
numDuplicates = sum(counts(binsOfDuplicates))
If you have an old version, you can use histc(), which has now been deprecated:
n = 7
r = randi(100,n,1)
% Test case
r = [30 17 94 28 28 19 19]
counts = histc(r, min(r):max(r))
binsOfDuplicates = counts >= 2
numDuplicates = sum(counts(binsOfDuplicates))

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Distribution Plots에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by