0

I have a cell array that contains a long list of strings. Most of the strings are in duplicates. I need the indices of instances of a string within the cell array.

I tried the following:

[bool,ind] = ismember(string,var);

Which consistently returns scalar ind while there are clearly more than one index for which the contents in the cell array matches string.

How can I have a list of indices that points to the locations in the cell array that contains string?

2
  • 4
    Is var the cell array? Then, use ismember(var,string). Commented Apr 7, 2015 at 22:32
  • Ok, then passing it through find does the job. Thanks! Commented Apr 7, 2015 at 22:36

3 Answers 3

2

As an alternative to Divakar's comment, you could use strcmp. This works even if some cell doesn't contain a string:

>> strcmp('aaa', {'aaa', 'bb', 'aaa', 'c', 25, [1 2 3]})
ans =
     1     0     1     0     0     0
Sign up to request clarification or add additional context in comments.

Comments

0

Alternatively, you can ID each string and thus have representative numeric arrays corresponding to the input cell array and string. For IDing, you can use unique and then use find as you would with numeric arrays. Here's how you can achieve that -

var_ext = [var string]
[~,~,idx] = unique(var_ext)
out = find(idx(1:end-1)==idx(end))

Breakdown of the code:

  • var_ext = [var string]: Concatenate everything (string and var) into a single cell array, with the string ending up at the end (last element) of it.

  • [~,~,idx] = unique(var_ext): ID everything in that concatenated cell array.

  • find(idx(1:end-1)==idx(end)): idx(1:end-1) represents the numeric IDs for the cell array elements and idx(end) would be the ID for the string. Compare these IDs and use find to pick up the matching indices to give us the final output.


Sample run -

Inputs:

var = {'er','meh','nop','meh','ya','meh'}
string = 'meh'

Output:

out =
     2
     4
     6

Comments

-1

regexp would solve this problem better and the easy way.

string  = ['my' 'bat' 'my' 'ball' 'my' 'score']
expression = ['my']

regexp(string,expresssion)
ans = 1 6 12

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.