MATLAB Find Exact String in Cell Array
Cell arrays in MATLAB store data of various data types as a cell. These cells could contain data of different types but belong to the same array. Now, this article is focused on finding an exact string in a cell array in MATLAB. This can be done easily by using a combination of two MATLAB functions, the strcmp() and find() functions. Let us see how the same is done
s_log = strcmp(<array>,<string>)
index = find(s_log)
This will return a vector with indices of all string elements that exactly match the given string. The strcmp() function takes an array and a string as input. Then it compares the string with all values in the passed array and returns a logical array with 1 on matched cells and 0 on unmatched ones. See below to understand the same.
This should return a vector [1 0 1] as the string str appears twice in the array arr on indices 1 and 3.
Now, we can use the find function to get the indices of non-zero elements from this logical array, which will be the same as the indices of appearance of our ‘str’ string.
As it can be verified, the string ‘geeks’ appear on two indices 1 and 3, and the same result is given by our program. Let us take another example where we find the string ‘devil’ in a given cell array.