2

I have a <465x1> cell array. For check each element, I want to check whether it is unique or a repeated element.

0

1 Answer 1

6

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Nice explanation, note that you can also find the truly unique values without find, by using U(count==1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.