0

There is a char matrix. Each row is a word. All the words/rows have the same length.

Is there anyway to find a target word in this matrix using find() function?

Say M=[o k a y; g o o d; h a v e]; A target word W='have'; Is there any function to search W in M and return the row index?

When I try index = find(isequal(W,M)) and index = find(isequal(W,M(:,:))), they both return empty array.

I know that I can use linear search, i.e. to compare row by row, just wonder if there is a built-in function to solve this problem. Thanks!

Autonomous
  • 8,935
  • 1
  • 38
  • 77
user3813057
  • 891
  • 3
  • 13
  • 31
  • possible duplicate of [Find given row in a matrix](http://stackoverflow.com/questions/6209904/find-given-row-in-a-matrix) – knedlsepp Jan 21 '15 at 01:22
  • Please accept the most suitable answer by clicking the check-mark on the left hand side of an answer. – Autonomous Jan 21 '15 at 18:05

2 Answers2

1

You need to compare M with a string. I am assuming M contains of individual characters as follows:

M=['o' 'k' 'a' 'y'; 'g' 'o' 'o' 'd'; 'h' 'a' 'v' 'e']

and W='have'

So in order to compare each row of M with W, you need to use strcmp. For that, you need M to be a cell array. You can convert each row of M into a cell array by using mat2cell.

equalRows=strcmp(W, mat2cell(M,ones(1,size(M,1)),size(M,2)));

% Answer

equalRows =

 0
 0
 1

Use find command on the above output to get the indices.

Autonomous
  • 8,935
  • 1
  • 38
  • 77
1

Another approach would be to use ismember. Assuming that M is a character array like you have defined, you would thus do:

W = 'have';
[~,idx] = ismember(M, W, 'rows');

The first input is the character array defined, the second input is the string we are searching for, and we choose 'rows' as the flag as we want to search on a row basis. Each word is defined in one row. The first output is true/false that is of the same size as M that tells you whether or not we have found the word indexed by that row in M is a match to the one you're searching for. Because we only want to know where that word is, we can suppress that first output. idx tells you which row the word was found.

When we call this function, we get:

idx = 

3

This means that the third row contains the word you're looking for. However, if you're dead set on using find, consider using ismember in conjunction with find:

W = 'have';
idx = find(ismember(M, W, 'rows'));

idx = 

3

However, the advantage with the above approach is that it will find all locations that match the particular word you're looking for.

rayryeng
  • 102,964
  • 22
  • 184
  • 193