MATLAB: Writing a function on an arbitrarly sized set of two dimensional vectors, with output size being set dependent

basicfunctionpairwise distance

haha I hope people here don't get tired of my inane questions too quickly..
Many of my scripts involve calculating euclidean distances between points. I want to do this more efficiently in the future, so I thought that I would write a function that takes a set of 2d vectors and outputs the distances between each point in the set.
my first problem is not knowing how to tell the function that the number of input variables should be variable… and then defining the number of outputs accordingly.. (n inputs –> n choose 2 outputs).
Then, is there a better way of defining each output? Could I automate the index calls in each calculation, or package inputs in such a way as to only have one operation to perform?
if true
%Ideally, I don't want to specify '5 inputs.. 10 outputs'.. but rather
%'n inputs, (n*n-1)/2 outputs).
function [ d12,d13,d14,d15,d16,d17,d23,d24,d25,d26,d27,d34,d35,d36,d37,d45,d46,d47,d56,d57,d67 ] = untitled4(x1,x2,x3,x4,x5,x6,x7)
%UNTITLED4 calculate the euclidean distance between all n choose 2 pairs of
%points.
%
%
d12=sqrt(sum((x1-x2).^2))
d13=sqrt(sum((x1-x3).^2))
%etc.. etc all the way to d67..or, ideally, d(n-1)(n) for n inputs
%is there a way to automate the indices, so that x13 automatically calls up
%x1 and x3? Should I be packaging my position vectors into a bookkeeping
%vector, and applying one operation to the whole vector bundle of vectors?
end

Best Answer

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:
D = pdist(X)
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); % If a full matrix is wanted
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) = ...