IDL

Negative Array Index in IDL

Chris blew my mind this morning when he showed me what happens if you use negative numbers to index an array in IDL (in versions lower than 8!). I would argue that it gives something that you don’t want, this is how you fix it.

Normally, if you just try to index an array with a single number you’d get an error message:

x = INDGEN(10)
PRINT, x[-1]
% Attempt to subscript X with <LONG     (          -1)> is out of range.
% Execution halted at: $MAIN$

However, if you again try printing x, but this time use an array of negative numbers, something entirely different happens…

x=INDGEN(10)
print,x[[-1,-2]]
0    0

No error messages, and it “successfully” prints out to the screen. It “converts” the unsuitable negative numbers to the nearest suitable number, i.e. 0 and 0 (this also works if you try to index the array with an array of numbers greater than the number of elements, i.e. in this case (for example) [11,12] – it would “convert” these numbers to the last element number of the array and print that twice). However, I would argue that is not what you want to happen and you’d like an error message to come up to avoid this accidentally happening (as was happening in the code Chris was using when he discovered this) – I know that in IDL 8 there is a whole feature in place for negative array indexes, which does various things, but this is for earlier versions of IDL.

Luckily there is quite a simple fix for this:

COMPILE_OPT STRICTARRSUBS

Then if you do the same again:

x=INDGEN(10)
print,x[[-1,-2]]
% Array used to subscript array contains out of range subscript: X.
% Execution halted at: $MAIN$

Again, something that I would argue is very useful! Indeed I’ve added the above command to my startup file.

One thought on “Negative Array Index in IDL

  1. I’m not that much of a online reader to be honest but your blogs really
    nice, keep it up! I’ll go ahead and bookmark your site to come back later on. Many thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.