5

I may be going about this the wrong way, but I'm trying define and fill arrays within a loop.

for i = 0,39 do begin

xx = long(findgen(n+1l)*sx + line1x[i]) 
sz = size(xx)
arrayname = 'line' + strtrim(i,2)
arrayname = findgen(3,sz[1])
arrayname[0,*] = xx
arrayname[1,*] = yy
arrayname[2,*] = vertline

endfor

This obviously won't work, but is there a way to use the string defined by 'line' + strtrim(i,2) to create and fill a new array upon each iteration? In this case I'd have 40 arrays with names line0...39. The difficult part here is that sz[1] varies, so I can't simply define one large array to hold everything.

cHao
  • 84,970
  • 20
  • 145
  • 172
Mike
  • 51
  • 1
  • 2

2 Answers2

3

In idl 8.0 or later you could use the HASH datatype for this.

Your code would looks like this:

array_dict = hash()
for ii = 0,39 do begin
  xx = long(findgen(n+1l)*sx + line1x[ii]) 
  sz = size(xx)
  arrayname = 'line' + string(1, FORMAT='(i02)')
  array = findgen(3,sz[1])
  array[0,*] = xx
  array[1,*] = yy
  array[2,*] = vertline

  array_dict[arrayname] = array
endfor

You can now access your arrays by name:

line = array_dict['line01']
amicitas
  • 13,053
  • 5
  • 38
  • 50
2

Well, there's always the execute function, if you're in the mood for a filthy hack (and don't need it to run on an unlicensed virtual machine installation).

But have you considered declaring a 1-D array of pointers, where each element points to one of your 3 by sz subarrays? That gives you some of the benefit of one big array, without the constraint of all the subarrays having to have the same shape. It might look something like this...

ptrs=ptrarray(40) ; Allocate an array of 40 pointers, initialized to null

for i = 0,39 do begin
  ; calculate sz, xx, yy, vertline
  dummy=findgen(3,sz[1])
  dummy[0,*] = xx
  dummy[1,*] = yy
  dummy[2,*] = vertline
  ptrs[i]=ptr_new(dummy) ; create copy of dummy on the heap, storing pointer in ptrs[i]

endfor

; To access the i-th subarray...

(*ptrs[i])[0,*] = new_xx
(*ptrs[i])[1,*] = new_yy
(*ptrs[i])[2,*] = new_vertline
Jim Lewis
  • 43,505
  • 7
  • 82
  • 96