[Fwd: How to make a read variable av lvalue?]

Przemek Klosowski przemek at jazz.ncnr.nist.gov
Thu Jan 24 08:44:34 CST 2008


   Svante Signell wrote:
   >
   > I have the following problem when coding in Octave/Matlab. After reading
   > a string from an external file into a variable, like x=fscanf(...)
   > resulting in x='string' how can I use this variable content as an
   > lvalue, like x.a='something', where x is replaced by its string value,
   > resulting in string.a='something' instead of x.a='something'.

As others suggested, you have picked the slow and intricate solution,
which is probably an overkill, so I would suggest to reassess whether
you really need the eval(). I am guessing that you want a flexible
namespace for your variables, but the same goal would be accomplished
if you used a hash array, like in Perl or Tcl:

 $x="foobar"                                   set x foobar
 $myVariables{$x} = 'something'                set myVariables($x) 1

Given the first-class hash arrays, you can implement all the other 
compound structures: $myVariables{$x}{field}, etc.

Octave doesn't have a built-in hash array type, but it comes pretty
close with the variant structure construct: similarly to the examples
above, you can have a structure with fields determined by a variable:

       x='abc';
       myVariables.(x)='something'

The added advantage of this approach relative to what you proposed
is that it creates a sort of a namespace: all related variables are
collected under the common 'root' name ('myVariables' in the example
above); you can pass them all together as a variable to subroutines, 
make them global, etc.


More information about the Help-octave mailing list