In IDL, how can I access a variable given its name? - string

I would like to convert a string to a variablename, so it can be read as a already restored variable.
So, I look through a file, and look at all the files. I use RESTORE to use the file in IDL, restore names this object as something slightly different. It names it as an object which we'll call map_1 (in the code it's called filerestore_name). This is related to the file name and I can recreate this variable name - however, its saved as a string.
Now, I pass this onto the make_cool_video procedure. However, althoughthis string now is exactly the same as the varialbe name, its still a string!.
Thus, as its a string, the procedure can't work.
filenames=FILE_SEARCH('rxrt*')
filenames_withoutextension = STREGEX(filenames,'rxrt_[0-9]+[a-zA-Z_]+',/EXTRACT,/FOLD_CASE)
restore, '/home/tomi/Documents/actualwork/'+filenames_withoutextension(18)+'.idl_sav',
filerestore_name = STRJOIN(STRSPLIT(filenameswithout(18),'_[0-9]+',/EXTRACT,/REGEX),'')
PRINT, filerestorename
make_cool_video, EXECUTE(filerestore_name),filename=filerestorenames, outdir='/path/to.file/'
retall
What I tried: using the RESTORE function and the associated RESTORED_OBJECTS to store pointers in an array, and then referring to the array. But I couldn't get the restore function to form an array.
Using EXECUTE(filerestore_name) however, this doesn't convert it as I was expecting.

I would recommend using SCOPE_VARFETCH() instead (it isn't as limited as EXECUTE() and is probably more efficient). You can do something like:
make_cool_video, (SCOPE_VARFETCH(filerestore_name)), filename=filerestorenames, outdir='/path/to.file/'

I wrote this, then immediately thought of the answer.
So,
Convert everything to a string:
string1 = "makecooljes, "+ filerestore_name, outdir='file/to/path/'"
result= EXECUTE(string1)

Related

Passing argument to lua function after evaluating function in string

I have functions process and matrix. The following code works
process(matrix({{2,4,6},{8,10,12},{14,16,20}}))
However the following doesn't work.
n='matrix({{2,4,6},{8,10,12},{14,16,20}})'
process(n)
It throws some error. The reason is obvious that process takes n as string rather than the output of the function matrix. So the basic difficulty involved here is about evaluating string from variable n and then give it as argument to the function process. Here loadstring function is of no use as matrix is local function and can't be referred from loadstring.
Is there any work around for this? I hope that I have clearly stated the problem here. It is about evaluating (or unloading) string and then passing it as argument to another function. Any help will be appreciated. Thanks.
as matrix is local function
Lua takes local declarations seriously. If a variable is declared local, it can only be accessed by code which is statically within the local scope of that variable. Strings which you later turn into code are not statically in the local scope and therefore cannot access local variables.
Now, with Lua 5.2+, you can provide load with a second parameter, a table which represents the global environment against which that Lua chunk will be built. If that table contains a matrix value, then the loaded string can access it. For Lua 5.1, you'd have to use setfenv on the function returned to load to accomplish a similar effect. The Lua 5.2+ method would look like this:
local env = {matrix = matrix}
local func = load("return matrix({{2,4,6},{8,10,12},{14,16,20}})", nil, "t", env)
process(func())
Note the following:
You must create an explicit table which is the global environment. There's nothing you can pass that says "make my locals available"; you have to put every local you'd like to access there. Which is, generally speaking, why you pass these things as parameters or just make them globals.
You explicitly need the "return " there if you want to get the results of the call to matrix.
You have to call the function. Functions are values in Lua, so you can freely pass them around. But if you want to pass the results of a function to another function, you have to actually call it.

Lua: returning or storing REPL/loadstring string output in a string variable

The same question already asked here
Lua: Executing a string and storing the output of the command in a variable
But I want the function loadstring somehow return the result in string form that may be assigned to a string variable later to use further, what it returns is a function.
Below code is an example:
ret = assert(loadstring(str_cmd))()
ret is a function:(
How can I get the REPL/loadstring output in string form?
If all output from str_cmd comes from calls to print, redefine print before loading str_cmd to save all output in a table. After running str_cmd, use the table in table.concat for instance.
Instead of redefining print you can provide an environment to run str_cmd in. You'll probably need to make that environment inherit from the global environment.

Renaming a structure in MATLAB using an existing string

I have a structure in MATLAB called dat. I want to rename dat as an existing string.
Existing_str='NewName'
$(Existing_str)=dat
This fails as I don't think MATLAB lets me use the dollar sign in this way. The code below creates a copy of dat literally called Existing_str and destroys the Existing_str in the process.
Existing_str=dat
While the code below generates a collosal empty structure which clearly is not a copy!
eval(Existing_str)=dat
In the task I am actually trying to perform I don't know the name of the existing_str in advance so that is not a solution.
You were almost there with your `eval'. What you want is:
eval([Existing_str '=dat;']);
This works because you're composing a string inside your square brackets. If you just looked at the resulting string, it would look like NewName=dat; The eval command simply tells Matlab to evaluate the string as if you typed it into the command line.
You can use dynamic field naming (Bas's suggestion), and avoid eval:
For example, if you have just loaded a structure dat from a file 'somefile.ext' with some custom parsing function:
filename = 'somefile.ext'; % presume you actually have a list of files from dir or ls
dat = yourfunction(filename);
[~, name, ~] = fileparts(filename);
alldat.(name)=dat;
This is equivalent to:
alldat.somefile = dat;
Except that we've just automatically taken the name from the filename (in this case just by stripping off the path/extension, but you could do other things depending on the pattern of the filename).
The bonus of this is that you can then, say, with a structure that has fields alldat.file1, alldata.file2, alldat.file3, all of which have a subfield, say, size do things like this:
names = fieldnames(alldat)
for n = 1:length(names)
alldat.(names{n}).mean = mean(alldata.(names{n}).size);
end
Every sub-structure now has a field, mean, which contains the mean of the data. If you had a bunch of different named structures you would need to eval everything you wanted to do to them collectively, and the code becomes difficult to read and maintain.
The other option is a cell array. Here's an easy trick:
dat = % whatever you do to make this structure
alldat{end+1} = dat;
This just appends the new dat onto the end of an existing cell array. {end+1} ensures it doesn't overwrite existing data.

How to save strings in matrixes in matlab

I want to have a matrix/cell, that has strings inside that I can access and use later as strings.
For instance, I have one variable (MyVar) and one cell (site) with names inside:
MyVar=-9999;
site={'New_York'; 'Lisbon'; 'Sydney'};
Then I want to do something like:
SitePosition=strcat(site{1},'_101'}
and then do this
save(sprintf('SitePosition%d',MyVar),);
This doesn't work at all! Is there a way to have strings in a matrix and access them in order to keep working with them if they were a string?
This:
MyVar=-9999; site={'New_York'; 'Lisbon'; 'Sydney'};
SitePosition = strcat(site{1},'_101');
save(sprintf('SitePosition%d',MyVar));
Works fine and yields SitePosition-9999.mat, note the syntax changes in lines 2 and 3.
Is there something else you're expecting?
EDIT: Based on your comment
Check out the documentation for save regarding saving specific variables
New example:
MyVar=-9999;
site={'New_York'; 'Lisbon'; 'Sydney'};
SitePosition = strcat(site{1},'_101');
save(SitePosition,'MyVar');
Creates New_York_101.mat with only the variable MyVar in it.

automating string and number concatenation

I'm having some trouble automating a matlab script which should prompt the user for the variable they are interested in, as well as the date range they want. I then want the script to concatenate their answers within a naming convention for the file they will ultimately load.
variable=input('please input variable of interest');
% temp
start=input('please state the start date in the form yymmdd: ');
%130418
enddate=input('please state the end date in the form yymmdd: ');
%140418
file=sprintf('%s_dailydata_%d_%d.csv',variable,start,enddate);
%so I thought 'file' would look like: temp_dailydata_130418_140418.csv
vardata=load(file);
the two numbers representing the dates are not causing any issues, but the fact that 'variable' is a string is. I know if I put apostrophes before and after 'temp' when I'm promted, it will work, but I have to assume that the end user won't know to do this. I tried putting curly braces around 'please input your variable..', but that didn't help either. Obviously this approach assumes that the date being requested exists in a filename.
Can anyone offer any advice? Perhaps the sprintf function is not the best option here?
Don't use 'end' as a variable name, it is a reserved name and using it could create conflicts with any function or logic block you're defining.
If you know your input is going to be a string: from the documentation for input()
str = input(prompt,'s')
Returns the entered text as a MATLAB string, without evaluating expressions.
As for knowing whether or not the file exists, that's something you'd have to incorporate some error logic for. Either a try/catch block with your load() call or you could use uigetfile() to get the filename.

Resources