X
PrevPrev Go to previous topic
NextNext Go to next topic
Last Post 04 May 2007 01:28 PM by  anon
What is the string_to_number function in IDL?
 1 Replies
Sort:
You are not authorized to post a reply.
Author Messages

anon



New Member


Posts:
New Member


--
04 May 2007 01:28 PM
    I have data arrays such as b1, b2, b3,...b100. To work on a loop computing b2/b1, b3/b1,....b100/b1, I first did this: FOR i=1, n DO BEGIN my_data='b'+strtrim(string(i),1) ENDFOR Now the string my_data has become b1, b2,..., but how to convert the string my_data to reference array data b1, b2...? I had been using Igor Pro and its $num2str(my_data) operation to achieve this conversion, but haven't found how to do this in IDL; or I can go around with some other IDL functions? Thanks for you reply.

    Deleted User



    New Member


    Posts:
    New Member


    --
    04 May 2007 01:28 PM
    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
    You are not authorized to post a reply.