Reputation: 419
suppose I have a vector of string as follows
'1 2'
'1'
'1'
'1'
'1'
'1'
'1'
'1'
'1'
'1'
how can I obtain the frequency of the strings from this vector? Unique() isnt working and gives the error Error using cell/unique Input A must be a cell array of strings.
Upvotes: 0
Views: 152
Reputation: 221574
Though kyamagu's answer looks like the simplest to follow, I am bringing this for the love of bsxfun
and vectorization
-
all_nums = char(INPUT_CELLARRAY);
unique_nums = unique(all_nums,'rows');
t1 = all_nums-'0';
t2 = permute(unique_nums-'0',[3 2 1]);
strings = cellstr(unique_nums)
count = squeeze(sum(all(bsxfun(@eq,t1,t2),2),1))
Output
strings =
'1'
'1 2'
count =
9
1
Upvotes: 1
Reputation: 551
I guess you contain a non-char element in your vector. You should first convert your vector to a valid cellstr.
string_vector = your_vector(cellfun(@ischar, your_vector));
[unique_strings, ~, indices] = unique(string_vector);
frequencies = accumarray(indices(:), 1);
Upvotes: 4