MATLAB: I need some help to understand algorithm here

MATLABmatlab algorithm

I just wonder what that function does? I tried so many examples and could not get it. Thanks for your help.
function result = funct(array)
result=0;
for i=2:length(array)
for j=1:i-1
if array(j)==array(i)
result=result+1;
end
end
end
result=length(array)-result;
end

Best Answer

funct([1 2 3])
ans = 3
funct([1 1 2])
ans = 2
funct([1 1 1])
ans = 0
funct([1 2 1])
ans = 2
funct([1 1 2 2])
ans = 2
funct([1 2 2 2])
ans = 1
funct([1 2 2 2 2])
ans = -1
function result = funct(array)
result=0;
for i=2:length(array)
for j=1:i-1
if array(j)==array(i)
result=result+1;
end
end
end
result=length(array)-result;
end
Start at the end of the array. Count how many of the entries before the current element duplicate the current element, and total those up as you move towards the left. Subtract that number from the length of the array.
Notice from that last example that duplications get counted more than once.
[1 2 2 2 2]
^ there are 3 duplicates of the 2 before this point, so count 3
^ there are 2 duplicates of the 2 before this point, so count 2
^ there is 1 duplicate of the 1 before this point, so count 1
That is a total of 6 duplicates counted for a vector of length 5, and 5-6 = -1.
There is another way of expressing this that does not rely on the order of the elements:
For each unique value, accumulate (number of repetitions)*(number of repetitions-1)/2 . Subtract that all from the total number of entries. (number of repetitions)*(number of repetitions-1)/2 is nC2, nchoosek(repetitions, 2)
[1 2 2 2 2] - 1 has 1 repetition, 1*(1-1)/2 = 0. 2 has 4 repetitions. 4*(4-1)/2 = 4*3/2=6 . length 5 - (0+6) -> -1