%% Find Nearest Words by Edit Distance
% Create a simple spelling corrector using an edit distance searcher with a list of known words.
% Create an edit distance searcher from a list of known words and set the maximum edit distance to 2. To include swaps in the edits, set the 'SwapCost' option to 1.

vocabulary = ["A" "of" "some" "list" "words"];
maxDist = 2;
eds = editDistanceSearcher(vocabulary,maxDist,'SwapCost',1);

% Find the indices and distances of the nearest words to a set of new words.

words = ["A" "list" "of" "som" "new" "worsd"];
[idx,d] = knnsearch(eds,words)

% The words "A", "list", and "of" are all in the searcher vocabulary already, so the edit distance for these are zero. The words "som" and "worsd" are each a single edit from a word in the searcher vocabulary (a single insert and swap respectively). Finally, the word "new" requires more than two edits (the maximum distance) to change it into a word in the searcher vocabulary, so the returned index is NaN with edit distance Inf.
% To correct the spelling of the words, replace them with matched words.

idxKnown = ~isnan(idx);
words(idxKnown) = eds.Vocabulary(idx(idxKnown))

% Copyright 2018 The MathWorks, Inc.