3
votes

Like the title says. How do I find the index of a specific element in a matlab cell array? The content of the cell array contains both strings and numbers.

Toy example:

database = cell(4,2)
database(1,1:2) = {'Song', 'Rating'}
database(2:4,1) = {'Song1'; 'Song2'; 'Song3'}
database(2:4,2) = {1; 2; 5}

functionIWant(database, 'Song2') % Should return [3,1] or something similar

I know I can convert it to a matrix, iterate over it and thereby find the right index. I'm wondering however if there is any faster method working directly on cell arrays.

2
+1 for including toy example. All questions should do thatLuis Mendo

2 Answers

3
votes

Try this -

[r,c] = find(strcmp(database,'Song2'))

Output -

r =
     3
c =
     1
1
votes

You can try something like that:

str='Song2';
Match=cellfun(@(x) strcmp(str, x), database, 'UniformOutput', 0);

And get the index of the match:

[row, col]=find(cell2mat(Match))

If you want the matching element of column 2, just do:

database(row, 2)