]> Creatis software - CreaPhase.git/blob - octave_packages/strings-1.1.0/editdistance.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / strings-1.1.0 / editdistance.m
1 ## Copyright (C) 2006 Muthiah Annamalai <muthiah.annamalai@uta.edu>
2 ##
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
6 ## version.
7 ##
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 ## details.
12 ##
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn {Function File} {[@var{dist},@var{L}] =} editdistance (@var{string1}, @var{string2}, @var{weights})
18 ## Compute the Levenshtein edit distance between the strings @var{string1} and
19 ## @var{string2}. This operation is symmetrical.
20 ##
21 ## The optional argument @var{weights} specifies weights for the
22 ## deletion, matched, and insertion operations; by default it is set to
23 ## +1, 0, +1 respectively, so that a least editdistance means a 
24 ## closer match between the two strings. This function implements
25 ## the Levenshtein edit distance as presented in Wikipedia article,
26 ## accessed Nov 2006. Also the levenshtein edit distance of a string
27 ## with an empty string is defined to be its length.
28 ## 
29 ## The default return value is @var{dist} the edit distance, and
30 ## the other return value  @var{L} is the distance matrix.
31 ##
32 ## @example
33 ## @group
34 ##          editdistance('marry','marie') 
35 ##          ##returns value +2 for the distance.
36 ## @end group
37 ## @end example
38 ##
39 ## @end deftypefn
40
41 function [dist, L] = editdistance (str1, str2, weights)
42   if(nargin < 2 || (nargin == 3 && length(weights)  < 3) )
43     print_usage();
44   end
45   
46   L1=length(str1)+1;
47   L2=length(str2)+1;
48   L=zeros(L1,L2);
49   
50   if(nargin < 3)
51     g=+1;%insertion
52     m=+0;%match
53     d=+1;%deletion
54   else
55     g=weights(1);
56     m=weights(2);
57     d=weights(3);
58   end
59
60   L(:,1)=[0:L1-1]'*g;
61   L(1,:)=[0:L2-1]*g;
62   
63   m4=0;
64   for idx=2:L1;
65     for idy=2:L2
66       if(str1(idx-1)==str2(idy-1))
67         score=m;
68       else
69         score=d;
70       end
71       m1=L(idx-1,idy-1) + score;
72       m2=L(idx-1,idy) + g;
73       m3=L(idx,idy-1) + g;
74       L(idx,idy)=min(m1,min(m2,m3));
75     end
76   end
77   
78   dist=L(L1,L2);
79 endfunction