MATLAB: How to create a vector with the number of repetition of a category

categoricalcategories;cell arraysMATLABtables

Assume that I have a categorical array X=categorical({'A','B','A','C'}). Through finding countcats(X) I can get the number of appearances of each category. I want to save this in a vector (Z) with the same length as X so that each term contains the number of appearances of the opposing category in X.
Z=[2,1,2,1]
How can I do this in the most efficient method (without for loop)?

Best Answer

X=categorical({'A','B','A','C'});
s = findgroups(X);
i4 = accumarray(s(:),1);
Z = reshape(i4(s),size(X));
or
Z = countcats(X);
Z = Z(findgroups(X));