Do not use numbered names for a list of variables. Using arrays is much nicer, faster and more flexible.
YOu can use the efficient pdist if you have the statistics toolbox:
where X is [x1;x2;x3; ...] which is preferrably to created dynamically, but much better is not to have a list of variables at all, but a vector all the time.
Without the toolbox for pdist:
function D = PairwiseDist(X)
n = size(X, 1);
D = zeros(n, n);
for i2 = 1:n
for i1 = i2 + 1:n
diff = x(i1, :) - x(i2, :);
D(i1, i2) = sqrt(diff * diff.');
D(i2, i1) = D(i1, i2);
end
end
You can create D as a vector containing the upper triangle of the matrix also. Allocate it accordingly before the loops, start with "index = 0" and then inside the loops:
index = index + 1;
D(index) = ...
Best Answer