## Finding the location of matched values in two different vectors

I have been looking for a command in SAS/IML which finds the location of the matched values in two different vectors.

I came across this website: http://stackoverflow.com/questions/4952548/value-matching-in-sas-iml where the same question was asked and the suggested answer was to use XSECT function to find the intersection of the two sets. However, XSECT function gives the common elements between two sets rather that giving the location of those elements.

For example, in the following code:

proc iml;

x={10 11 12 13 12 13 14 15};

v={12 13};

z=xsect(x,v);

print z;

quit;

the SAS result is: Z= {12    13}, but I’mlooking for a vector like {3  4  5  6} which is the location of common elements of vector V in vector X.

Would anybody help me with the appropriate function inSAS/IML?

Thank you very much.

2 REPLIES 2

## Finding the location of matched values in two different vectors

In SAS 9.3, the function you want is the ELEMENT function teamed up with the LOC function:

idx=loc(element(x,v));

If you haven't upgraded to SAS 9.3,  you can use the UNIQUE-LOC technique, which I recently blogged about.

## Finding the location of matched values in two different vectors

For example, here's one one approach:

u = unique(v);

free idx;

do i = 1 to ncol(u);

k = loc(x=u);

idx = idx || k;

end;

print idx;

This code isn't maximally efficient because it doesn't preallocate the IDX array (see http://blogs.sas.com/content/iml/2011/06/20/pre-allocate-arrays-to-improve-efficiency/).

Still it's not too bad. Use this if your vectors aren't too long. If this step is being used in the innermost loop of a long-running computation, write back. The code can be improved, but at the cost of additional complexitites.

From The DO Loop