user1661303
user1661303

Reputation: 549

MATLAB: finding index of an element in a multidimensional cell array with mixed data types

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.

Upvotes: 3

Views: 7846

Answers (2)

Cape Code
Cape Code

Reputation: 3574

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)

Upvotes: 1

Divakar
Divakar

Reputation: 221614

Try this -

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

Output -

r =
     3
c =
     1

Upvotes: 3

Related Questions