expanding arrays to take all permutations for add/subtract operations

a = reshape(1:9,3,3)
b = reshape(0:0.1:0.5,2,3)
arows = size(a,1);
brows = size(b,1);
for m = 1:arows
for n = 1:brows
c(m,n,:) = a(m,:) - b(n,:);
end
end
distance = 1./sqrt(sum(c.^2,3))
I want to calculate the Euclidean distance of all combinations of points in two coordinate arrays, a (mx3) and b (nx3). I know how to do this in a loop (see above), but is there some nice/fast/readable vectorized operation that lets me do this, sort of how vector outer products lets you expand to all permutations of elementwise multiplication?
(1:3)'*(1:5)
ans =
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
Obviously, I could expand each dimension, but I don't think that is very readable:
x = repmat(a(:,1), 1, brows) - repmat(b(:,1)', arows, 1);
y = repmat(a(:,2), 1, brows) - repmat(b(:,2)', arows, 1);
z = repmat(a(:,3), 1, brows) - repmat(b(:,3)', arows, 1);
distance = 1./sqrt(x.^2+y.^2+z.^2)

Answers (1)

distance = 1./squeeze(sum(bsxfun(@minus,a,permute(b,[3, 2, 1])).^2,2));

1 Comment

Haha his complaint about the more explicit solution was readability.. This is some seriously cryptic, 'matic code. I can't wait to confuse my coworkers with this one, seems to do the business.

Sign in to comment.

Categories

Find more on Deep Learning Toolbox in Help Center and File Exchange

Asked:

on 18 May 2015

Commented:

on 5 May 2017

Community Treasure Hunt

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

Start Hunting!