Pair-wise operation on two vectors that avoids double calculation

I have 1 vector and I would like to calculate the pair-wise difference.
This does the job, but it unnecessarily performs the calculation twice.
bsxfun(@minus, A, A')
Is there a way to do this only outputs a lower triangular matrix?

Answers (2)

I doubt there's a way that makes the effort worthwhile, but here is one possibility,
N=length(A);
map=tril(true(N));
[i,j]=find(map);
out=double(map);
out(map)=A(i)-A(j);

1 Comment

Hi Matt thanks for your answer. This does work indeed but it seems to run 10 times slower than using bsxfun directly. I guess I will just have to stick with the array manipulation in this case.

Sign in to comment.

This made me curious about how the JIT-compiler performs. This function shouldn't do too many extra operations:
function Adiffs = AAprimedifferences(A)
for i1 = length(A):-1:2,
for i2 = (i1-1):-1:1,
Adiffs(i1,i2) = A(i1) - A(i2);
end
end
I don't have time to do timings or such properly...

1 Comment

Hi Bjorn, this one runs about 4 times slower than bfxfun. The test code is here:
A = rand(10000,10000);
method == 0;
tic
if method == 0
out = AAprimedifferences(A);
else
out = bsxfun(@minus, A, A');
end
toc

Sign in to comment.

Asked:

on 14 Jul 2015

Commented:

on 14 Jul 2015

Community Treasure Hunt

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

Start Hunting!