BookmarkSubscribeRSS Feed
Reza
Calcite | Level 5

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
Rick_SAS
SAS Super FREQ

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.

Rick_SAS
SAS Super FREQ

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.

sas-innovate-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

Register now!

Multiple Linear Regression in SAS

Learn how to run multiple linear regression models with and without interactions, presented by SAS user Alex Chaplin.

Find more tutorials on the SAS Users YouTube channel.

From The DO Loop
Want more? Visit our blog for more articles like these.
Discussion stats
  • 2 replies
  • 1054 views
  • 3 likes
  • 2 in conversation