# expanding arrays to take all permutations for add/subtract operations

조회 수: 3(최근 30일)
Knut 18 May 2015
댓글: Victor 5 May 2017
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)

로그인 to comment.

### 답변(1개)

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

#### 댓글 수: 1

Victor 5 May 2017
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.

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.