Question

I'm very new to IDL.

Effectively what i want to do is have an if statement that checks if the current index I is in an array.

In Python it would look something like the following:

if this_num in xartifact:
   print 'Is an x artifact'
elif this_num in yartifact:
   print 'Is a y artifact'
else:
   print 'Is neither'

I know that you can nest ifs in IDL:

IF P1 THEN S1 ELSE $

IF P2 THEN S2 ELSE $

IF PN THEN SN ELSE SX

I just can't find out if there is an in operator or sane way of doing this.

Cheers

Was it helpful?

Solution

I would use the count parameter in WHERE similar to the above example:

a = 2
b = [1, 2, 3, 5]
ind = where(a eq b, count)
print, count gt 0 ? 'a in b' : 'a not in b'

OTHER TIPS

IDL can be a bit overwrought with if statements. The basic "if then else if then" statement, as you said, could be something like:

if a eq 0 then print, 'the variable a equals 0' else $
if a eq 1 then print, 'the variable a equals 1' $
else print, 'the variable is something else'

For multiple lines within an if statement, instead of using a $ to continue the line, you could use something like:

if a eq 0 then begin
  print, 'the variable a equals 0'
  print, 'more stuff on this line'
endif else if a eq 1 then begin
  print, 'the variable a equals 1'
  print, 'another line'
endif else begin
  print, 'a is something else'
  print, 'yet another line'
endelse

Lastly, to evaluate if a variable is in a vector depends on exactly what you want to do and what is in your array, but one option is to use the where function. One example to show how it works:

a=2
b=[1,2,2,3]
result = where(a eq b)
print, result
if result[0] ne -1 then print, 'a is in b' $
else print, 'a is not in b'

There is probably a much better way of doing this as well. Perhaps a case statement.

The answer provided by @mgalloy definitely works, however there is a simpler solution, which takes advantage of the total procedure and only involves one line of code.

a = 2
b = [1, 2, 3, 5]

if total(b eq a) eq 1 then print, 'Yes' else print, 'No'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top