[Scilab-users] How to use a string variable as a childname in a structure?

Samuel Gougeon sgougeon at free.fr
Thu Dec 1 22:40:22 CET 2016


Hello Christoph,

Le 01/12/2016 18:25, christophk a écrit :
> Hi there,
>
> is there a way to use a string variable during a children-call in a scilab
> structure?
> Here is an example for what i want to do:
>
> function myvalue = getchild(myparent,mychild)
>      //this function doesn't work and is just meant to show the idea of what
> I want to do:
>     //"mychild" is a string to call for a childname of "myparent", which is a
> struct. Is this at all possible?
>      myvalue = myparent.mychild;
> endfunction
>
> s = struct('a',[1 2 3],'b', [4 5 6]);
> //how do I change my getchlidren function for this to work
> x = getchild(s,'a'); // equivalent for x = s.a;
> y = getchild(s,'b'); // equivalent for y = s.b;

What you name "children" is usually named a "field" of a structure or of 
another tlist or mlist type.
You don't need any "getchild()" function to address / extract / feed the 
field of a structure.
It is a built-in syntax. Just do
myparent(mychild)
And that's it.

Examples:
s.r = [%pi %e %i]   // equivalent to s("r")
s.t = ["Hi" "Hello"]

// Now,
myField = "r";
s(myField)

// The syntax with ("..") allows using some fieldnames with spaces:
s("big cities") = ["Mexico" "Paris" "Tokyo"]
// s."big cities"  does not work, but the following does:
s("big cities")

UTF-8 chararacters are forbidden in field names with Scilab 5, but 
Scilab 6 accepts them:

-->getversion("scilab")
  ans  =
     5.    5.    2.    1.428D+09

-->s.réel = %pi
     !--error 2
Invalid factor.

// In another session:
--> getversion("scilab")
  ans  =
    6.   0.   0.   1.477D+09

--> s.réel = %pi
  s  =
   réel: [1x1 constant]

Isn't this great ?! :)

HTH
Samuel Gougeon




More information about the users mailing list