Is there a function in Octave that returns the position of the first occurrence of a string in a cell array?
I found findstr
but this returns a vector, which I do not want. I want what index
does but it only works for strings.
If there is no such function, are there any tips on how to go about it?
As findstr
is being deprecated, a combination of find
and strcmpi
may prove useful. strcmpi
compares strings by ignoring the case of the letters which may be useful for your purposes. If this is not what you want, use the function without the trailing i
, so strcmp
. The input into strcmpi
or strcmp
are the string to search for str
and for your case the additional input parameter is a cell array A
of strings to search in. The output of strcmpi
or strcmp
will give you a vector of logical
values where each location k
tells you whether the string k
in the cell array A
matched with str
. You would then use find
to find all locations of where the string matched, but you can further restrain it by specifying the maximum number of locations n
as well as where to constrain your search - specifically if you want to look at the first or last n
locations where the string matched.
If the desired string is in str
and your cell array is stored in A
, simply do:
index = find(strcmpi(str, A)), 1, 'first');
To reiterate, find
will find all locations where the string matched, while the second and third parameters tell you to only return the first index of the result. Specifically, this will return the first occurrence of the desired searched string, or the empty array if it can't be found.
octave:8> A = {'hello', 'hello', 'how', 'how', 'are', 'you'};
octave:9> str = 'hello';
octave:10> index = find(strcmpi(str, A), 1, 'first')
index = 1
octave:11> str = 'goodbye';
octave:12> index = find(strcmpi(str, A), 1, 'first')
index = [](1x0)