Find Indices of Value in Array - Idl
I Am Learning Idl Through Some Inherited Code. in Other Languages (Python, Matlab), It Is Easy to Find the Indices Associated with a Value of Interest in an...
I am learning IDL through some inherited code. In other languages (python, MATLAB), it is easy to find the indices associated with a value of interest in an array. However, I cannot seem to find any simple function or method to do this in IDL. For example:
A = [55, 6, 762, 35, 155, 1, 867, 35]
I know that the value 155 is in A, but I am interested in its location [x,y]. How can I easily access this information?
The only thing I can think of that is similar is finding a MAX value within an array.
B = max(A,location)
where the second argument (location) gives the index of the maximum value in A. However, I want to be able to do this with any value, not just max.
I am aware of the VALUE_LOCATE function, but that requires the array to be monotonic which is not the case here.
I have tried using WHERE and ARRAY_INDICES, among other things, but I don't think I am using them correctly (or they just don't do what I am asking for).
Thank you.
2 Answers
Of course, I figured it out right after posting this. Using the WHERE function solved the problem. If anyone searches for this in the future:
C = where(A eq desired_value)
You can keep track of the indices in the original array then use VALUE_LOCATE in the following way.
b = LINDGEN(N_ELEMENTS(a))
s = SORT(a)
c = b[s]
d = a[s]
Now just define your search value(s), say, as the variable v then you can do the following:
v = 155
i = VALUE_LOCATE(d,v) ;; index of sorted array
j = c[i[0]] ;; index of original, unsorted array
Then you can check your results by doing:
PRINT,';; ',a[j[0]],d[i[0]]
;; 155 155
The only annoying caveat of VALUE_LOCATE is that if the array a has any NaNs in it, the search will fail or return bad values so be careful of that.
If you know the value for which you are searching is an integer, then using WHERE will also work, for example:
good = WHERE(a EQ v[0],gd)
PRINT,';; ',a[good[0]]
;; 155
The caveat with using WHERE is if you only know the approximate search value and the array contains single- or double-precision floating point values. Sometimes your search will turn up null because you don't have the exact match.