Looking for a word in a 2D array

16 views (last 30 days)
Alex Flores
Alex Flores on 28 Apr 2017
Commented: Alex Flores on 2 May 2017
Hey guys, so I am having trouble finishing my code for this problem: Write a function called WordSearch.m that looks for a word in a 2-D character array. The function should take in two inputs:
  1. an m by n character array (letters in the Englishalphabet) that is the word search grid and
  2. a cell array of words that should be searchedfor.
The function looks for each word from the cell array in the 2-D character array. It searches for the word horizontally (left-to-right) and vertically (top-to-bottom). The function then returns a cell array that stores the row and column indices of the first character of the word if the word was found and an empty array ([]) if the word was not found. Your function should ignore the case of the letters. Your function does not need to find words ordered diagonally or backwards (right-to-left or bottom-to-top). Example:
testArray=['c' 'E' 'L' 'l'; 'S' 'U' 'r' 'I'; 'e' 'f' 'd' 'S'; 'T' 'A' 'G' 't'];
function cellArray= WordSearch(array,words)
[s1,s2]= size(words)
[m,n]= size(array)
for ii=1:s2 %word
found = 1 %true
for r:m %row
if (strcmpi(array(r,:), words(ii))==1) %L to R
found = 0 %turns false
elseif found
for c:n %column
if (strcmpi(array(:,c), words(ii))==1)% T to B
Im pretty stuck and do not know where to go from here.
Thanks in advance :)

Answers (1)

Joseph Cheng
Joseph Cheng on 28 Apr 2017
I would take a look at the function strfind(), and lower() or upper().
strfind() will return the starting index value of the found string.
so if i had
testArray = ['c' 'E' 'L' 'l'; 'S' 'U' 'r' 'I'; 'e' 'f' 'd' 'S'; 'T' 'A' 'G' 't']
words = {'Cell','set','sell'}
%replacing the 1 there with the an incremental index of the for loop
you can see that col returns with 1 and col is empty because the string was not found vertically (note the transpose and retreival of the of the column array)
with that you can then see which one you have, row or column and which column/row you fed it from the for loop.
  1 Comment
Alex Flores
Alex Flores on 2 May 2017
where do you suggest I insert this?

Sign in to comment.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!