## A noisy sine wave as query
idx<-seq(0,6.28,len=100);
query<-sin(idx)+runif(100)/10;
## A cosine is for template; sin and cos are offset by 25 samples
template<-cos(idx)
plot(template); lines(query);
## Find the best match (approx 1sec on Pentium 4)
## keep = TRUE so we can make a density plot later on
alignment<-dtw(query,template,keep=TRUE);
## Display the mapping
plot(alignment$index1,alignment$index2);
## That's all: 25 samples off-diagonal alignment
lines(1:100-25,col="red")
## Contour plots of the global cost
## A profile of the cumulative distance matrix
## similar to: plot(alignment,type="density") or dtwPlotDensity(alignment)
contour(alignment$costMatrix,col=terrain.colors(100),x=1:100,y=1:100,
xlab="Query (noisy sine)",ylab="Template (cosine)");
lines(alignment$index1,alignment$index2,col="red",lwd=2);
## More plots on dtw.plot!
#########
## An hand-checkable example
ldist<-matrix(1,nrow=6,ncol=6); # Matrix of ones
ldist[2,]<-0; ldist[,5]<-0; # Mark a clear path of zeroes
ldist[2,5]<-.01; # Forcely cut the corner
ds<-dtw(ldist); # DTW with user-supplied local cost matrix
da<-dtw(ldist,step="a"); # Also compute the asymmetric
plot(ds$index1,ds$index2,pch=3); # Symmetric: alignment follows the marked path
points(da$index1,da$index2,col="red"); # Asymmetric: visiting 1 is required twice
ds$distance;
da$distance;
Run the code above in your browser using DataLab