MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

A fast way to compare two vectors

  • To: mathgroup at smc.vnet.net
  • Subject: [mg121655] A fast way to compare two vectors
  • From: Yasha Gindikin <gindikin at gmail.com>
  • Date: Sat, 24 Sep 2011 22:32:46 -0400 (EDT)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • Reply-to: comp.soft-sys.math.mathematica at googlegroups.com

I'm looking for a hyper-fast way to compare two vectors using Mathematica built-in functions. The problem arises in the calculation of the Hamiltonian matrix elements of a many-particle quantum system.

Consider two rows of equal length n, a[[p1] and a[[p2]]. Their elements are integers from 1 to M, put in an increasing order, without repeats. E.g., a[[p1]]={1,2,3,6,7,9} and a[[p2]]={1,2,4,7,8,9}. I need to find the number of different elements (4 in the example) and, if this number is less or equal to 4, their positions ((3,4) and (3,5) in the example). The simplest way looks like this:

diff = Intersection[a[[p1]], a[[p2]]];
R = Dimensions[diff][[1]];
If[R<5,d1 = Complement[a[[p1]], diff];
d2 = Complement[a[[p2]], diff];
k1 = Position[a[[p1]], d1[[1]]]; k2 = Position[a[[p1]], d1[[2]]];
k3 = Position[a[[p2]], d2[[1]]]; k4 = Position[a[[p2]], d2[[2]]]];

This is slow, since four search operations are used (and because the ordering of the elements is not taken advantage of). Is there a built-in function that quickly finds the differences between the two vectors?

Thank you.
Regards,
Yasha.




  • Prev by Date: Re: help with integration
  • Next by Date: Re: 1-liner wanted
  • Previous by thread: Re: Error Message on Magnification
  • Next by thread: Re: A fast way to compare two vectors