comp.lang.idl-pvwave archive
Messages from Usenet group comp.lang.idl-pvwave, compiled by Paulo Penteado

Home » Public Forums » archive » Finding Common Elements in Two Arrays
Show: Today's Messages :: Show Polls :: Message Navigator
E-mail to friend 
Return to the default flat view Create a new topic Submit Reply
Re: Finding Common Elements in Two Arrays [message #2201 is a reply to message #2111] Wed, 01 June 1994 16:23 Go to previous messageGo to previous message
dan is currently offline  dan
Messages: 27
Registered: March 1993
Junior Member
Subject: Finding Common Elements in Two Arrays
Newsgroup: comp.lang.idl-pvwave:

kucera@stars.gsfc.nasa.gov (Terry Kucera) writes :

> I'm looking for a quick way to compare two arrays in IDL, A and B,
> and determine which elements of B are also in A,
> so if:
> A=[2,1,3,5,3,8,2,5]
> B=[3,4,2,8,7,8]
> I would get [0,2,3,5], because 3, 2, and 8 are in A as well as B.

> I can do this with loops, but that takes too long for big arrays. Does anyone
> have a way to do this using array functions or perhaps an external routine?
> Terry Kucera
> kucera@stars.gsfc.nasa.gov

OK, basically what we have here is the problem of finding the intersection
of two sets of numbers. Assuming that the two sets contain non-negative
long or short integers, here is a slick (and tricky) way to do it :


IDL> A=[2,1,3,5,3,8,2,5]
IDL> B=[3,4,2,8,7,8]

IDL> ; PART 1. Find the numbers common to both sets.

IDL> set_length = Max([Max(A), Max(B)]) + 1L
IDL> set_1 = Bytarr(set_length)
IDL> set_2 = Bytarr(set_length)
IDL> set_1(A) = 1B
IDL> set_2(B) = 1B
IDL> common_num = Where(set_1 AND set_2)
IDL> Print, common_num
2 3 8

IDL> ; PART 2. Find where the common numbers exist in array B.

IDL> index_arr1 = Replicate(1, N_Elements(B)) # common_num
IDL> index_arr2 = b # Replicate(1, N_Elements(common_num))
IDL> common_sub = Where(index_arr1 EQ index_arr2) MOD N_Elements(B)
IDL> Print, common_sub
2 0 3 5


IDL> ; PART 3. Get ALL the common numbers in array B (including duplicates)

IDL> Print, B(common_sub(SORT(common_sub)))
3 2 8 8


Try it, you'll like it !

------------------------------------------------------------ -------------------
"If I don't read the net news, somebody else will."
____ _____ _____
/ \ /\ | \ | \ (Dan Carr)
/ /__\ |____/ |____/ (Research Systems)
\ / \ | \ | \ (Boulder, Colorado)
\____/ / \ | \ | \ (dan@rsinc.com)

------------------------------------------------------------ -------------------
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Finding common elements in two arrays
Next Topic: Please help with buggy widget code

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ] [ PDF ]

Current Time: Fri Oct 10 04:21:13 PDT 2025

Total time taken to generate the page: 1.11967 seconds