Sorting 2D waves, by using one column as a key

This snippet sorts a multicolumn 2D wave, by using one of the columns as a key (the normal sort operation only sorts 1D waves). The default is alpha numeric sorting, but that's easily fixed by changing the sort options. Please note that this snippet has now been edited to cope with any type of wave to be sorted; it works on numerical and text waves. The original is at the bottom.

Function MDsort(w,keycol, [reversed])
    Wave w
    variable keycol, reversed
   
    variable type
   
    type = Wavetype(w)
 
    make/Y=(type)/free/n=(dimsize(w,0)) key
    make/free/n=(dimsize(w,0)) valindex
   
    if(type == 0)
        Wave/t indirectSource = w
        Wave/t output = key
        output[] = indirectSource[p][keycol]
    else
        Wave indirectSource2 = w
        multithread key[] = indirectSource2[p][keycol]
    endif
   
    valindex=p
    if(reversed)
        sort/a/r key,key,valindex
    else
        sort/a key,key,valindex
    endif
   
    if(type == 0)
        duplicate/free indirectSource, M_newtoInsert
        Wave/t output = M_newtoInsert
        output[][] = indirectSource[valindex[p]][q]
        indirectSource = output
    else
        duplicate/free indirectSource2, M_newtoInsert
        multithread M_newtoinsert[][] = indirectSource2[valindex[p]][q]
        multithread indirectSource2 = M_newtoinsert
    endif
End



=======Here is the original version=======
Function MDtextsort(w,keycol, [reversed])
    Wave/t w
    variable keycol, reversed
 
    make/t/free/n=(dimsize(w,0)) key
    make/free/n=(dimsize(w,0)) valindex
 
    key[] = w[p][keycol]
    valindex=p
 
    if(reversed)
        sort/a/r key,key,valindex
    else
        sort/a key,key,valindex
    endif
   
    duplicate/free/t w, M_newtoInsert
 
    M_newtoinsert[][] = w[valindex[p]][q]

    duplicate/o/t M_newtoInsert,w
End
Us, too! We were looking for the same thing (numerical version). Maybe a critical mass of comments will persuade the WM folks to add a 2D option to the regular Sort operation.....
Yes, I programmed this as well quite recently. Precisely for the 2D text waves. I must say that this snippet gave me more insight, what the values in "valindex" actually are. :-)

========
Time to find out, whether you are dead right, or just dead.

Just in case someone finds that here. Since IP7 this can be done with the builtin SortColumns.

Forum

Support

Gallery

Igor Pro 9

Learn More

Igor XOP Toolkit

Learn More

Igor NIDAQ Tools MX

Learn More