3

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
Quantum_Oli
  • 7,964
  • 2
  • 21
  • 43
  • Relevant? Doesn't use Outer http://mathematica.stackexchange.com/questions/21861/fastest-way-to-calculate-matrix-of-pairwise-distances – dr.blochwave Nov 15 '16 at 22:21

2 Answers2

4

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}} *)
MarcoB
  • 67,153
  • 18
  • 91
  • 189
4

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 *)
Simon Woods
  • 84,945
  • 8
  • 175
  • 324
  • +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! – Quantum_Oli Nov 16 '16 at 13:00