Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define array name within a loop

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.

like image 841
Mike Avatar asked Aug 04 '10 22:08

Mike


People also ask

Can we declare array in for loop in Java?

You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.

Can an array be used in a for loop?

Each time the for loop runs, it has a different value – and this is the case with arrays. A for loop examines and iterates over every element the array contains in a fast, effective, and more controllable way. This is much more effective than printing each value individually: console.

What is looping through an array called?

We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.


1 Answers

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']
like image 150
amicitas Avatar answered Sep 21 '22 15:09

amicitas