Matlab: Write a function that creates a string out of letters in a 2-dimensional
ID: 3764800 • Letter: M
Question
Matlab: Write a function that creates a string out of letters in a 2-dimensional array of characters. Your function should take an array of characters, the indices of a starting letter, a length, and a direction as inputs, and it should return a string of letters. To simplify your direction inputs, 1 = left-to-right, 2 = right-to-left, 3 = down, 4 = up, 5 = top left to bottom right, 6 = bottom right to top left, 7 = top right to bottom left, and 8 = bottom left to top right.
The length is for how long the Word that you are finding is
Explanation / Answer
function s = GetWord(chr,i,j,len,dir)
s = ''
[x,y] = size(chr);
if (dir == 1)
for k = j:y
s = s + chr(i,k);
len = len - 1;
if (len == 0)
break;
end
end
elseif (dir == 2)
k = j;
while (k > 0)
s = s + chr(i,k);
len = len - 1;
if (len == 0)
break;
end
k = k - 1;
end
elseif (dir == 3)
for k = i:x
s = s + chr(k,j);
len = len - 1;
if (len == 0)
break;
end
end
elseif (dir == 4)
k = i;
while (k > 0)
s = s + chr(k,j);
len = len - 1;
if (len == 0)
break;
end
k = k - 1;
end
elseif (dir == 5)
while (i <= x && j <= y)
s = s + chr(i,j);
i = i + 1;
j = j + 1;
end
elseif (dir == 6)
while (i > 0 && j > 0)
s = s + chr(i,j);
i = i - 1;
j = j - 1;
end
elseif (dir == 7)
while (i > 0 && j <= y)
s = s + chr(i,j);
i = i - 1;
j = j + 1;
end
elseif (dir == 8)
while (i <= x && j > y)
s = s + chr(i,j);
i = i + 1;
j = j - 1;
end
end
end