Borrar filtros
Borrar filtros

Using a string shortcut for nested structure

12 visualizaciones (últimos 30 días)
Jos
Jos el 23 de En. de 2020
Comentada: Jos el 24 de En. de 2020
Hi all,
I tried using the search function but to no avail. Hopefully you can help me with this one.
Suppose I have a structure called 'tmp':
tmp = struct();
tmp.ahoy.matey = 'hello';
Would it be possible to create a sort of an 'alias' or shortcut using a string to get to 'hello' in a direct way, and also reassign it? I tried:
blah = 'ahoy.matey';
tmp.(blah) = 'hi';
But that gets me an error.
Invalid field name: 'ahoy.matey'.
Sure, I can evaluate it:
eval(['tmp.' blah])
ans =
'hello'
But I cannot really change 'hello' into something different.
Is there a way to do this?
Thank you!
Best regards,

Respuesta aceptada

Stephen23
Stephen23 el 23 de En. de 2020
Editada: Stephen23 el 23 de En. de 2020
For accessing a field of one specific structure (which can be nested) you should use dynamic fieldnames:
For accessing multiple arbitrary fields of arbitrarily nested structures the most robust way is to use setfield and getfield, for which you will need to split the string into the separate field names (because each field belongs to a different structure, they cannot be provided as one string) which can be provided as a comma-separated list, for example:
>> tmp = struct();
>> tmp.ahoy.matey = 'hello';
>> str = 'ahoy.matey';
>> spl = regexp(str,'\.','split');
>> getfield(tmp,spl{:})
ans = hello
>> tmp = setfield(tmp,spl{:},'world');
>> getfield(tmp,spl{:})
ans = world
See also:
TIP: even better than passing around that string would be to just pass the cell array spl.
  1 comentario
Jos
Jos el 24 de En. de 2020
This is a nice, simple and eloquent way of reffering to nested structs. Many, many thanks!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by