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.
Best Answer