MATLAB: How to count the number of times a string occurs in a cell array in a vectorized format

MATLAB

I have a vector, 'A', of length 'n' with non-unique strings. Some entries will repeat but not necessarily all. I would like to create a cell array that lists the unique strings and another cell array that lists how many times each string occured in vector 'A'.
I would like to perform this in a vectorized method as the cell array is quite large and using a FOR loop to compare each unique entry against the entire vector is very time consuming.

Best Answer

Applying the UNIQUE, STRCMP, and REPMAT functions, finding the number of string repetitions in cell arrays can be performed in a vectorized format.
Using the UNIQUE function, one can obtain cell vector, 'unique_names', of length 'm' from vector 'original_names'. The contents of 'unique_names' will be every string that appears at least once.
unique_names = unique(original_names);
Then using the REPMAT function, one can make a matrix, 'X', where the rows are vector 'original_names' repeated 'm' times resulting in an mxn matrix.
X = repmat(original_names,length(unique_names),1);
Similarly, we make a matrix, Y, with vector 'unique_names' repeated over the columns 'n' times, again, creating an mxn matrix.
Y =repmat(unique_names,1,size(original_names,2))
Next, one can use the STRCMP function to compare matrix 'X' and 'Y'. Taking the sum along the rows will give the quantity of times a given string in the cell array occurred.
quantity = num2cell(sum(strcmp(X,Y),2)');
Please see the attached file for a test sample.
Alternatively you can use the HIST-function to count how many times each string occured in the input vector 'A'.
[a b c] = unique(A)
d = hist(c,length(a))
a contains the the same vector A, but without repetitions.
d contains the count of repetitions.