accessing "sub-structs"

Ben Abbott bpabbott at mac.com
Sat Jun 6 10:47:53 CDT 2009


On Jun 6, 2009, at 11:37 AM, Thorsten Meyer wrote:

> Hi,
>
> given a structure
>  s = struct("a", 1, "b", 2, "c", 3)
>
> I would like to access a substructure of s containing only the  
> fields "b" and "c".
>
> Of course, this can be done by
>  substruct = struct("b", s.("b"), "c", s.("c"));
> or in an assignment:
>  [s.b, s.c] = deal(10, 20);
>
> However, how can I do it, if I do not know beforehand, which fields  
> I want to
> access? E.g., I would like to create a function, where a structure and
> cellstring containing a list of fieldnames is given as input  
> arguments, and the
> corresponding substructure is returned.
> Of course, I can generate a command string like the above, with  
> sprintf and eval it:
>  substruct = eval(['struct (', ...
>      sprintf('"%s", s.("%s"),', [fields; fields]{:})(1:end-1), ...
>      ")"]);
> But is there a more elegant way to do it?
>
> regards
>
> Thorsten

Does the following meet your needs?

x = "a";
y = "b";
z = "c";

s = struct (x, 1, y, 2, z, 3)

substruct = struct (y, s.(y), z, s.(z))
substruct =
{
   b =  2
   c =  3
}

clear s
[s.(y), s.(z)] = deal(10, 20);
s =
{
   b =  10
}

s =
{
   b =  10
   c =  20
}

Ben



More information about the Help-octave mailing list