You are on page 1of 2

/home/tuhin/swc-kebab/phd/entropy-1/kmp2d.

m Page 1 of 2 Mon 10 Mar 2014 03:16:29 PM CST 1 %{ 2 % Tuhin Paul, University of Saskatchewan 3 m = kmp2d(W, S) 4 searches W in S : USES row-wise comparisons 5 returns the 1-based first position of W in S. 6 if no match, returns 0 7 % Input arguments must be matrices (1D/2D arrays). 8 % and 9 % No of columns of input arguments must match because 10 % the search uses ROW-WISE comparisons. 11 12 Examples: 13 W = 'ABCDABD'; 14 % W = 'PARTICIPATE IN PARACHUTE'; 15 S = 'ABC ABCDAB ABCDABCDABDE'; 16 % note that the arguments are column vectors here: 17 m = kmp2d(W', S'); 18 19 % example with 2-D matrix arguments: 20 S = [1 2 3; 4 5 6; 7 8 9; 1 2 4; 1 2 3; 4 5 6; 1 2 4; 21 7 8 9; 3 0 6; 1 2 3; ]; 22 W = [1 2 3; 4 5 6; 1 2 4;]; 23 % here arguments need not be transposed: 24 m = kmp2d(W, S) 25 26 27 REF: http://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm 28 %} 29 function [m] = kmp2d(W, S) 30 31 % Input arguments must be matrices (1D/2D arrays): 32 assert( ismatrix(S) && ismatrix(W), ... 33 'Input arguments must be matrices (1D/2D arrays)' ); 34 35 % No of columns of input arguments must match because 36 % the search uses ROW-WISE comparisons: 37 assert( size(S,2) == size(W,2), ... 38 'No of columns of input arguments must match because the search uses ROW-WISE compar isons' ); 39 40 41 strlen = size(S, 1); 42 wordlen = size(W, 1); 43 T = pmtable(W) - 1; 44 45 m = 1; 46 i = 0; 47 48 while (m+i) <= strlen 49 if W(i+1, :) == S(m+i, :) 50 if i == (wordlen - 1) 51 %m = m+1; % because of 1 based indexing 52 return ; 53 end 54 i = i + 1; 55 else 56 m = m + i - T(i+1); 57 if T(i+1) > -1 58 i = T(i+1); 59 else 60 i = 0; 61 end 62 end 63 end 64 65 % did not match: 66 m = 0; 67 end
- 1 -

/home/tuhin/swc-kebab/phd/entropy-1/kmp2d.m Page 2 of 2 68 69 % construct partial match table for the word W: 70 function [T] = pmtable(W) 71 wordlen = size(W, 1); 72 T = zeros(wordlen, 1); 73 T(1) = 0; 74 T(2) = 1; 75 76 pos = 3; 77 cnd = 1; 78 79 while pos <= wordlen 80 if W(pos-1, :) == W(cnd, :) 81 cnd = cnd+1; 82 T(pos) = cnd; 83 pos = pos+1; 84 85 elseif cnd > 1 86 cnd = T(cnd); 87 else 88 T(pos) = 1; 89 pos = pos + 1; 90 end %if 91 end %while 92 end 93

Mon 10 Mar 2014 03:16:29 PM CST

- 2 -

You might also like