3

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.

1
  • 1
    +1 for including toy example. All questions should do that Commented Jun 2, 2014 at 16:52

2 Answers 2

3

Try this -

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

Output -

r =
     3
c =
     1
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, strcmp works directly on cell arrays? Convenient.
@Jigg Exactly! Easier this way I guess :)
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.