Search code examples
arraysstringmatlabdata-structuresindices

How do I use matlab ismember in data structures with multiple nested fields?


In matlab I have the following 2 data structures b and c defined as follows.

b(1).b = struct('c',{'a', 'b', 'c'})
c(1).b = struct('c',{'b', 'a', 'c'})

Now I want to use ismember to find out if the elements of b(1).b.c are contained in c(1).b.c and if so, which indices of c(1).b.c each of the elements belong to.

For example: b(1).b(1).c = a, I want to backtrace this to structure c to find which index of structure c 'a' belongs to (it should return 2 since 'a' is the second element of structure c).

I have tried

[~, ind] = ismember({b(1).b.c},{c(1).b.c})

which has worked for me previously with a different data structure but I now receive the following error:

*Error using cell/ismember>cellismemberR2012a (line 192)
Input A of class cell and input B of class cell must be cell arrays of      strings, unless one is a string.
Error in cell/ismember (line 56)
[varargout{1:max(1,nargout)}] = cellismemberR2012a(A,B);*

I am not sure why its not working. Does anybody know how to fix this? Thanks.


Solution

  • I found the following to work.

    First assigning b(1).b.c to an array S and then comparing that with the data structure c using ismember.

    S = [b(1).b.c]
    S = S'
    [~, ind] = ismember(S,{c(1).b.c})
    

    I have found this to work.

    Also,

    [~, ind] = ismember([b(1).b.c}],[c(1).b.c]) 
    

    does not give an error but all the values in ind are zero which is not true for the data.

    Thanks all for your input!