Re: Array indexing surprises [message #72482] |
Tue, 07 September 2010 16:32 |
Michael Galloy
Messages: 1114 Registered: April 2006
|
Senior Member |
|
|
On 9/7/10 4:01 PM, Larry Kneller wrote:
> I received this question from a guy I work with.
>
> The main thing I can't explain here is that if I index an array with
> too big
> a number where the index is an array, then it behaves as though there
> is
> no problem.
>
> Here is an example program to illustrate:
>
>
> pro jrdc_colors
>
> color=['red','white','blue']
>
> icol=[3]
> print,color[icol] ; blue
> ; NO ERROR, NO CRASH IN IDL 7 or 8!
>
> icol2 = [-3,-2,-1,0,1,2,3,4]
> print,color[icol2] ; red red red white blue blue blue
>
> print,color[-3] ; blue
> print,color[-2] ; white
> print,color[-1] ; red
>
> print,color[3] ; ERROR IN IDL 7 AND 8
> end
>
> I don't know whether this is a bug or it is working as
> planned. It seems like the first two examples in this
> code will cause problems with where statements.
Using out-of-bounds indices when indexing by an array or by a scalar are
handled differently. When indexing by an array, the default behavior is
to substitute 0 for negative indices and the last valid index for
indices larger than that.
This behavior can be changed for a given routine by placing
compile_opt strictarrsubs
in that routine. Then indexing an array by an array with out-of-bounds
values will be an error.
For indexing by negative scalars, the behavior changed in IDL 8.0.
Indexing by negative values is an error in pre-IDL 8.0, but in IDL 8.0,
a[-ind] is handled as a[n_elements(a) - ind]. Note that this could still
be out-of-bounds if ind is greater than the number of elements in a:
~$ idl
IDL Version 8.0, Mac OS X (darwin x86_64 m64). (c) 2010, ITT Visual
Information Solutions
IDL> a = findgen(10)
IDL> print, a[-1]
9.00000
IDL> print, a[-10]
0.00000
IDL> print, a[-11]
% Attempt to subscript A with <INT ( -11)> is out of range.
% Execution halted at: $MAIN$
Indexing by positive out-of-bounds scalars is always an error.
Mike
--
www.michaelgalloy.com
Research Mathematician
Tech-X Corporation
|
|
|