3
$\begingroup$

Could someone confirm for me whether DistanceMatrix is behaving differently in V11?

In V10 I could return the signed differenced between two vectors using

DistanceMatrix[u,v,DistanceFunction->Subtract]

However, in V11 the returned values are all positive. Using an undefined function f for DistanceFunction reveals that DistanceMatrix is adding the Abs internally in V11 thus prohibiting signed returns:

DistanceMatrix[Range[2], Range[3], DistanceFunction -> f]

V11 output

{{Abs[f[1, 1]], Abs[f[1, 2]], Abs[f[1, 3]]}, {Abs[f[2, 1]], Abs[f[2, 2]], Abs[f[2, 3]]}}

V10.3 output

{{f[{1}, {1}], f[{1}, {2}], f[{1}, {3}], f[{2}, {1}], f[{2}, {2}], f[{2}, {3}]}}

I feel like including Abs by default isn't very helpful as I could always add it in if I wanted it!

Thus I have two questions:

  1. Is there any way to remove it? I
  2. Is there a smarter way to get the signed differences of two lists - I know I can use Outer but have been using DistanceMatrix following the discussion here
$\endgroup$
1
4
$\begingroup$

This is a bit of a hack, and I am not sure how it will impact performance, but it goes around the "improvement" put in place in v.11:

ReleaseHold[
 DistanceMatrix[Range[2], Range[3], DistanceFunction -> HoldForm[Subtract]] /. Abs[a_] :> a
]

(* Out: {{0, -1, -2}, {1, 0, -1}} *)

Compare to the built-in in v.11:

DistanceMatrix[Range[2], Range[3], DistanceFunction -> Subtract]

(* Out: {{0, 1, 2}, {1, 0, 1}} *)
$\endgroup$
3
  • $\begingroup$ A similar hack: Block[{Abs = Identity}, DistanceMatrix[Range[2], Range[3], DistanceFunction -> Subtract] ] $\endgroup$
    – Jason B.
    Nov 15 '16 at 22:37
  • $\begingroup$ @JasonB Your suggestion is arguably more elegant as well. $\endgroup$
    – MarcoB
    Nov 16 '16 at 4:57
  • $\begingroup$ ReleaseHold and Block both great ways to get around the issue, thanks. ReleaseHold suffers a performance hit whereas Block does not. $\endgroup$ Nov 16 '16 at 12:58
4
$\begingroup$

Outer is pretty fast when used with Plus so I daresay Outer[Plus, u, -v] will be competitive:

u = Range[1000];
v = Range[2000];

RepeatedTiming[
 a = DistanceMatrix[u, v, DistanceFunction -> Subtract];]
(* {0.499, Null} *)

RepeatedTiming[
 b = Outer[Plus, u, -v];]
(* {0.00918, Null} *)

Abs[b] == a
(* True *)
$\endgroup$
1
  • $\begingroup$ +1 for pointing out that Outer[Plus, u, -v] is orders of magnitude faster than Outer[Subtract, u, v]. I like the methods of circumventing the Abs issue in MarcoB's answer but the Outer Plus route is by far the fastest! And what I'll use form now on! $\endgroup$ Nov 16 '16 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.