How to combine Matlab's build-in functions dtw and pdist?

17 views (last 30 days)
DS
DS on 16 Nov 2017
Commented: m qasim on 24 Apr 2020
Hi, I'm trying to perform hierarchical clustering on my data. I've tried several distance metrics, but now I would like to use the build-in function for dynamic time warping (Signal Processing Toolbox), by passing the function handle @dtw to the function pdist. Following problem occuried:
Error using pdist (line 391)
Error evaluating distance function 'dtw'.
Caused by:
Error using dtw (line 87)
The number of rows between X and Y must be equal when X and Y are matrices
Here is the code I'm using:
D = pdist(data,@dtw); %data is a 1184x38 double matrix, where 1184 is the number of time-series
Z = linkage(D,'ward');
res = cluster(Z, 'maxclust', numClusters); %e.g. numClusters = 5
Many thanks in advance!
  1 Comment
Dankur Mcgoo
Dankur Mcgoo on 5 Jul 2018
Did you end up solving your problem? I am facing the same issue.

Sign in to comment.

Answers (1)

Greg Dionne
Greg Dionne on 9 Aug 2018
You'll want to take the output of DTW and put it into a form that PDIST can recognize.
This should get you started:
function d = dtwdist(Xi, Xj, varargin)
[m,n] = size(Xj);
% preallocate
d = zeros(m,1);
for j=1:m
d(j) = dtw(Xi, Xj(j,:), varargin{:});
end
Use it like:
X = randn(118,38);
maxsamp = 10;
d = pdist(X,@(Xi,Xj) dtwdist(Xi,Xj,maxsamp,'squared'))
imagesc(squareform(d));
colorbar;
title('Distance Matrix')
  1 Comment
m qasim
m qasim on 24 Apr 2020
Hi ,help me to use a different distance metric in DTW algorithm like mahlanobis

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by