14

I am trying to find a string in a vector. For Eg:query = "ab" in vector = ["ab", "cd", "abc", "cab"]

The problem is: It is giving all the indices which have string "ab" when I use the function strfind(vector,query). In this case "ab" including "abc" and "cab". But i only want the index of "ab" not others. Is there any specific function for this in Octave?

user3713665
  • 147
  • 1
  • 7

1 Answers1

13

The problem is on your syntax. When you do vector = ["ab", "cd", "abc", "cab"], you are not creating a vector of those multiple strings, you are concatenating them into a single string. What you should do is create a cell array of strings:

vector = {"ab", "cd", "abc", "cab"};

And then you can do:

octave-cli-3.8.2>  strcmp (vector, "ab")
ans =

   1   0   0   0

Many other functions will work correctly with cell array of strings, including strfind which in this cases gives you the indices on each cell where the string "ab" stars:

octave-cli-3.8.2> strfind (vector, "ab")
ans = 
{
  [1,1] =  1
  [1,2] = [](0x0)
  [1,3] =  1
  [1,4] =  2
}
carandraug
  • 12,938
  • 1
  • 26
  • 38
  • this is fine. But can you please tell me like how to append an element in this cell. Is there any inbuilt function? – user3713665 Sep 04 '14 at 20:41
  • 1
    Also if there are multiple matches or you're searching for multiple strings have a look at the `ismember` function. With regards to appending to the matrix you can do this: vector{end+1} = 'new string'. Have a look at [my answer to this question](http://stackoverflow.com/questions/25620636/how-to-use-cell-arrays-in-matlab/25621199#25621199) for more details. – Dan Sep 05 '14 at 07:59