Pair-wise operation on two vectors that avoids double calculation
Show older comments
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);
Bjorn Gustavsson
on 14 Jul 2015
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
Sam Li
on 14 Jul 2015
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!