MathGroup Archive 2011

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

Search the Archive

A fast way to compare two vectors

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.

  • 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