0

Here is some data.

A = {'asdf' 'qwer'};

When I use ==, I get

>> A == 'asdf'
Undefined operator '==' for input arguments of type 'cell'.

which is expected. A workaround is to do

>> ismember(A, 'asdf')

ans =

     1     0

How do you add a method for the cell class so that == defaults to calling ismember in the above fashion?

Alex
  • 15,186
  • 15
  • 73
  • 127
  • 1
    I wouldn't call `ismember` a workaround, I would call it the canonical way to do it. It has a different meaning to `==`. I don't think you can overload the `==` operator in MATLAB (I don't know for sure though) but I think it is a bad idea. You will make your code less reusable, less readable to others joining the project etc – Dan Nov 27 '15 at 06:59

2 Answers2

2

You can overload @eq for cell arrays by following the explanation in this answer.

Why is that a bad idea? ismember only works if there are strings inside the cell array, but not other data types. Also, it will make your code not portable, as for example I would not want to use code that overloads operators for built-in data types.

If you really want to have a cell-array-like data type, where you can use @eq as ismember, you can create your custom class myCellArray that subclasses cell and that guarantees that each element contains a string. Then, you can go and overload operators all you want.

Community
  • 1
  • 1
Jonas
  • 74,690
  • 10
  • 137
  • 177
  • 1
    I guess it would be possible to overload @eq for `cell` and not and other classes if you place it in the @cell folder. However, I would recommend it as little as you. Built in types as `cell` should have the same behaviour on all machines. – patrik Nov 27 '15 at 07:45
  • Thanks for the link. That is what I will do. The code is for personal convenience only. While doing the overloading I will throw a warning which will say: "== not defined for cell, using user defined routine" or something like that, which will remind me not to do it for code I intend to share. – Alex Nov 29 '15 at 22:14
1

If you want to test whether the string 'asdf' is in the cell array {'asdf','qwer'}, you should probably use the ismember function:

my_set = {'asdf','qwer'};
logical_result = ismember('asdf',my_set);

There are major stylistic problems with doing what you are suggesting:

  1. Defining the operator == in such a way that it isn't reflexive (i.e. A==A returns false) and isn't symmetric (A==B isn't the same as B==A) is bizarre.
  2. Your code won't be portable as it will require people hacking their def. of cell array to work. Almost no one will be willing to do this.
  3. Changing the code for cell array has the potential to introduce confusing errors down the line.
  4. Alternatively, putting in the time and effort into writing your own cell array wrapper/replacement class is possible, but would be a horrible waste of time and needlessly slow.
Matthew Gunn
  • 4,451
  • 1
  • 12
  • 30