MATLAB:How to check if a cell element already exists in a cell array?

4.3k views Asked by At

Hello community of stackoverflow,

I have a cell array Q, 5520x1 cell array, which consists of arrays like this for example:

K>> Q{1}

ans =

 0     3     1    84

and so on.

I'd really like to know, how would it be possible to check if an element of the cell array,like the above, already exists in Q? Because if it does exist, i do not add anything, but if yes, i had to add this element to the end of Q. How could this check be done properly? Short solutions, if possible of course, would be a little more appreciated.

Thanks in advance for your time, Nick

1

There are 1 answers

0
Luis Mendo On BEST ANSWER

I'm assuming that by "element" you mean the whole vector. So for example, given

Q = {[1 2 3], [4 5]}

the new vector [2 4 3] should be added, but [4 5] should not.

To do that check: denoting the new vector by new, use

alreadyExists = any(cellfun(@(x) isequal(x, new), Q));

Examples:

>> Q = {[1 2 3], [4 5]};
>> alreadyExists = any(cellfun(@(x) isequal(x, [2 4 3]), Q))
alreadyExists =
     0
>> alreadyExists = any(cellfun(@(x) isequal(x, [4 5]), Q))
alreadyExists =
     1