Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search a particular string in a vector(Octave)

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?

like image 550
user3713665 Avatar asked Sep 04 '14 19:09

user3713665


People also ask

How to search for a substring in a string Matlab?

k = strfind( str , pat ) searches str for occurrences of pat . The output, k , indicates the starting index of each occurrence of pat in str . If pat is not found, then strfind returns an empty array, [] . The strfind function executes a case-sensitive search.

How do you compare strings in octave?

To determine if two strings are identical it is necessary to use the strcmp function. It compares complete strings and is case sensitive. strncmp compares only the first N characters (with N given as a parameter). strcmpi and strncmpi are the corresponding functions for case-insensitive comparison.

Can you index a string in Matlab?

You can index into, reshape, and concatenate string arrays using standard array operations, and you can append text to them using the + operator.

What is find in octave?

To obtain a single index for each matrix element, Octave pretends that the columns of a matrix form one long vector (like Fortran arrays are stored). For example: find (eye (2)) ⇒ [ 1; 4 ] If two inputs are given, n indicates the maximum number of elements to find from the beginning of the matrix or vector.


1 Answers

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
}
like image 85
carandraug Avatar answered Oct 27 '22 21:10

carandraug