Clear all fields of a struct

83 visualizaciones (últimos 30 días)
Karl
Karl el 26 de Mzo. de 2014
Comentada: Azzi Abdelmalek el 26 de Mzo. de 2014
Hi,
I have a struct with a number of fields that I want populate, and then store, each iteration through a loop. I want the struct to be empty and available each iteration. Is there a function to clear all the fields? Or do I just declare the whole thing again?
I tried setting each feild individually to [], like
myStruct.a = [];
myStruct.b = [];
But it's actually faster to declare the whole thing new each iteration, as in:
myStruct = struct('a', [], 'b', []);
Or maybe there's a better approach all together?
Cheers, Karl

Respuesta aceptada

Karl
Karl el 26 de Mzo. de 2014
A colleague suggested this:
myStruct = structfun(@(x) [], myStruct, 'UniformOutput', false);
It's about the same speed-wise, maybe a little faster on average. But it's nice and neat :)
  1 comentario
Azzi Abdelmalek
Azzi Abdelmalek el 26 de Mzo. de 2014
clearing your variable doesn't make your code faster, maybe you need to pre-allocate
myStruct = structfun(@(x) zeros(1,100), myStruct, 'UniformOutput', false);

Iniciar sesión para comentar.

Más respuestas (1)

Azzi Abdelmalek
Azzi Abdelmalek el 26 de Mzo. de 2014
Editada: Azzi Abdelmalek el 26 de Mzo. de 2014
%example
a.b=1
a.c=2
a.d=3
%----------------
f=fields(a)
for k=1:numel(f)
a.(f{k})=[];
end
  1 comentario
Karl
Karl el 26 de Mzo. de 2014
Editada: Karl el 26 de Mzo. de 2014
Thanks for the reply. This approach does work, but it takes more or less the same amount of time as re-declaring the structure.
Surely there's a better way than resortimg to loops?

Iniciar sesión para comentar.

Categorías

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

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by