Is there a way to extract specific fields from a structure?
34 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
TastyPastry
el 23 de Jun. de 2016
Respondida: Itsik Adiv
el 3 de Sept. de 2018
I have a 1x1 structure with a large number of fields of which I'd like to extract some subset. I don't want to have to use
[myst.field1 myst.field2 myst.field3]...
Is there a way to shorten the code so I only have to type myst once and just extract the fields necessary? The structure name is nested within another structure so the code can get lengthy.
0 comentarios
Respuesta aceptada
Stephen23
el 23 de Jun. de 2016
Editada: Stephen23
el 23 de Jun. de 2016
Solution
>> S.a = 'Hello';
>> S.b = 'World';
>> C = {'a','b'};
>> D = cellfun(@(f)getfield(S,f),C,'UniformOutput',false);
>> horzcat(D{:})
ans = HelloWorld
Improvement
Note that if the fieldnames really are numbered like that then a much better solution would be to consider using a non-scalar array. A non-scalar structure is a much better way to store data, compared to numbered fieldnames. Using a non-scalar structure would avoid having to perform slow and complicated tricks like this, instead you could use the neat and fast methods shown in the link:
>> S(1).f = 'Hello';
>> S(2).f = 'World';
>> [S.f]
ans = HelloWorld
See how choosing the best data storage makes a huge difference to the quality of code!
2 comentarios
Stephen23
el 23 de Jun. de 2016
@TastyPastry: fair enough. Then my solution does exactly what your question asks for: it concatenates the fields together.
Más respuestas (2)
Itsik Adiv
el 3 de Sept. de 2018
You can use rmfield instead:
fieldsList = fieldnames(myst); myst = rmfields(myst, fieldnames{4:end});
Of course you can replace indices 4:end with any valid indexing logic you wish
0 comentarios
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!