There are two ways to do this in IDL, a traditional old way and a newer way that was developed just a couple of years ago. The old way has the disadvantage that it cannot be compiled for distribution in an IDL .sav Runtime program, while the new way can. Let's start with the new way, then, but before I start, let me quickly explain that the problem in your current code is that you are assigning a string in your loop:
my_data = 'b1'
my_data = 'b2'
etc.
while you really want to be EXECUTEing the variable copying statement:
my_data = b1
my_data = b2
etc.
So, here are the two methods:
1. Use SCOPE_VARFETCH, which can be compiled in a Runtime program, if necessary.
The syntax "myArray[i] = scope_varfetch('var')" will copy the value of a variable named "var" that is defined in the current scope (scope is where you are running in the current "call stack" - what routine call you are currently running in) into 'myArray'.
2. Use EXECUTE, which cannot be compiled in a .sav Runtime program:
EXECUTE treats its string argument as a command that should be run "on the fly" during the execution of the current program. The syntax for this approach is:
myCommand = 'myArray[i] = b' + strtrim(i, 2)
if ~execute(myCommand) then print, " ***ERROR executing '", myCommand, "' ***"
Here is an example of both approaches:
PRO ex_dynamic_var_assignment
seed = 1 ; Make 3 pseudo-random variables
b1 = fix(randomu(seed) * 100D)
b2 = fix(randomu(seed) * 100D)
b3 = fix(randomu(seed) * 100D)
my_data_via_varfetch = intarr(3)
my_data_via_execute = intarr(3)
for i = 1, n_elements(my_data_via_varfetch) do begin
varName = 'b' + strtrim(i,2)
my_data_via_varfetch[i - 1] = scope_varfetch(varName)
myCommand = 'my_data_via_execute[i - 1] = ' + varName
if ~execute(myCommand) then $
print, " ***ERROR executing '", myCommand, "' ***"
end
print, 'Bn variables: ', b1, b2, b3
print, 'my_data_via_varfetch: ', my_data_via_varfetch
print, 'my_data_via_execute: ', my_data_via_execute
END
James Jones
|