Calculate the intersection of two waves

The function below can be used to calculate the intersection of 2 one-dimensional integer waves, such as would be returned by the Extract operation using the /INDX flag. The intersection is stored in the resultWave parameter to the function. This wave must exist but will be redimensioned by the function as appropriate.


Make/O/N=5 wave1, wave2, wave3 wave1= {1, 2, 3, 4, 5} wave2 = {3, 4, 5, 6, 7} CalculateWaveIntersection(wave1, wave2, wave3) print wave3 wave3[0]= {3,4,5}

Suggestions for improvements to this function are welcome.

// Calculates the intersection of two 1D integer waves.  You might use this to determine
// common indices in two destWaves created by the Extract/INDX operation.
// @param wave1
//  First 1D integer wave.
// @param wave2
//  Second 1D integer wave.
// @param resultWave
//  A wave where the result will be stored.  This wave will be overwritten if it already contains
//  any data.  The function will change the this to an integer wave if it is not already.
Function CalculateWaveIntersection(wave1, wave2, resultWave)
    WAVE wave1
    WAVE wave2
    WAVE resultWave
    Variable wave1Rows = DimSize(wave1, 0)
    Variable wave2Rows = DimSize(wave2, 0)
    Variable longRows, shortRows
    if (wave1Rows > wave2Rows)
        Duplicate/O wave1, longWave
        WAVE shortWave = wave2
        longRows = wave1Rows
        shortRows = wave2Rows
        Duplicate/O wave2, longWave
        WAVE shortWave = wave1
        longRows = wave2Rows
        shortRows = wave1Rows
    // Sort values in longWave
    Sort longWave, longWave
    Redimension/I/N=(0) resultWave
    Variable n, numOutRows, longWaveRow
    For (n=0; n<shortRows; n+=1)
        longWaveRow = BinarySearch(longWave, shortWave[n])
        if ((longWaveRow) >= 0 && longWave[longWaveRow] == shortWave[n])
            Redimension/N=(numOutRows + 1) resultWave
            resultWave[numOutRows] = shortWave[n]
            numOutRows += 1
    KillWaves/Z longWave




Igor Pro 8

Learn More

Igor XOP Toolkit

Learn More

Igor NIDAQ Tools MX

Learn More