MATLAB: How to find the number of times an elements occurs in an array and copy to another array with same index

arraycopy to another arrayduplicate elements

What I need is to find the number of times the elements repeat themselves in an array and copy the count to another array with the same index. I'll illustrate what i want by example:
A[4]=[1 4 6 1 5]
B[6]=[2 0 0 1 1 1]
Here,1 appears twice in A, so B[1]=2, 2 doesn't appear so B[2]=0, 3 doesn't appear so B[3]=0, 4,5 and 6 appear once so B[4]=1,B[5]=1,B[6]=1.

Best Answer

If you have a later version of MATLAB:
>> A = [1 4 6 1 5]
A =
1 4 6 1 5
>> B = histcounts(A,max(A))
B =
2 0 0 1 1 1
Or the "not recommended" older histc:
>> B = histc(A,1:max(A))
B =
2 0 0 1 1 1