z8080
z8080

Reputation: 659

Finding all occurences of a string within a cell array (itself part of a struc)

I have the following structure

dataDens = 

     dens: [1x172 double]
    level: {1x172 cell}
     raga: {1x172 cell}

within which dataDens.raga consists of (reducing the number of columns below for simplicity)

Columns 1 through 3
    'Multani'    'Tori'    'Tori' 

I'd like to find the indices at which 'Tori' appears (that is, [2 3] for the example above). However, all of the commands I tried (below) either give an error, or return blank outputs. I think it's probably just a matter of adding/removing a curly bracket somewhere, or using some conversion; but I am at my wit's end, and hope someone can help clarify

indices = find(strcmp([dataDens.raga{:}], {'Tori'}))
indices = ismember('Tori', dataDens.raga)
[if,where] = ismember('Tori', dataDens.raga)

Upvotes: 0

Views: 39

Answers (1)

rinkert
rinkert

Reputation: 6863

The issue had indeed to do with brackets. [dataDens.raga{:}] will result in concatenation of the character arrays, like so:

>> [dataDens.raga{:}]
ans =
    'MultaniToriTori'

Using strcmp to compare this to 'Tori' will result in false, since there is no exact match. You can however compare the entire cell using strcmp, which will then return a boolean array, in which find can be used to obtain the indices of true entries:

indices = find(strcmp(data, {'Tori'}))

Alternatively, ismember would also work, but using ismember('Tori', dataDens.raga) you are checking whether 'Tori' is in dataDens.raga, not the other way around. Changing this to

ismember(dataDens.raga, 'Tori')

would again give you a boolean array, and find will obtain the indices you are looking for.

Upvotes: 1

Related Questions