-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdp.m
55 lines (50 loc) · 1.03 KB
/
dp.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
function [p,q,D] = dp(M)
% [p,q] = dp(M)
% Use dynamic programming to find a min-cost path through matrix M.
% Return state sequence in p,q
% 2003-03-15 [email protected]
% Copyright (c) 2003 Dan Ellis <[email protected]>
% released under GPL - see file COPYRIGHT
fprintf('[Dynamic Programming begins,....');
[r,c] = size(M);
% costs
D = zeros(r+1, c+1);
D(1,:) = NaN;
D(:,1) = NaN;
D(1,1) = 0;
D(2:(r+1), 2:(c+1)) = M;
% traceback
phi = zeros(r,c);
for i = 1:r;
for j = 1:c;
[dmax, tb] = min([D(i, j), D(i, j+1), D(i+1, j)]);
D(i+1,j+1) = D(i+1,j+1)+dmax;
phi(i,j) = tb;
end
end
% Traceback from top left
i = r;
j = c;
p = i;
q = j;
% h = waitbar(0, 'Dynamic programming');
while i > 1 & j > 1
tb = phi(i,j);
if (tb == 1)
i = i-1;
j = j-1;
elseif (tb == 2)
i = i-1;
elseif (tb == 3)
j = j-1;
else
error;
end
p = [i,p];
q = [j,q];
% waitbar((p-i)/p, h);
end
%close(h);
% Strip off the edges of the D matrix before returning
D = D(2:(r+1),2:(c+1));
fprintf(', and Finished! \n');