I have a <465x1> cell array. For check each element, I want to check whether it is unique or a repeated element.
1 Answer
Use unique for this purpose, it can work on cell arrays too:
[U, ic, iu] = unique(C);
Where C is your cell array. U is a new cell array with the same values as C but without repetitions. You can then count the occurrences of each value using histc:
[U, ic, iu] = unique(C);
count = histc(iu, 1:numel(ic))
Example
For the sake of the example, let's generate a random cell array of strings first:
strings = {'foo'; 'bar'; 'baz'; 'bang'};
C = strings(ceil(numel(strings) * rand(6, 1)))
This should generate something like this:
C =
'bang'
'baz'
'foo'
'bang'
'bar'
'foo'
Now we count the occurrences of each value in C:
C = strings(ceil(numel(strings) * rand(6, 1)));
[U, ic, iu] = unique(C);
count = histc(iu, 1:numel(ic))
This should result in:
U =
'foo'
'bar'
'baz'
'bang'
count =
2
1
1
2
which means that 'foo' and 'bang' are repeated twice, while the rest only once, which is correct.
If you are only interested in the truly unique values, you can do:
U(count == 1)
Which should return in our example:
'bar'
'baz'
Note that each element in count represents the corresponding value in U (not strings, they may have a different order).
1 Comment
find, by using U(count==1)