Clear all fields of a struct

조회 수: 89 (최근 30일)
Karl
Karl 2014년 3월 26일
댓글: Azzi Abdelmalek 2014년 3월 26일
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

채택된 답변

Karl
Karl 2014년 3월 26일
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
Azzi Abdelmalek
Azzi Abdelmalek 2014년 3월 26일
clearing your variable doesn't make your code faster, maybe you need to pre-allocate
myStruct = structfun(@(x) zeros(1,100), myStruct, 'UniformOutput', false);

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2014년 3월 26일
편집: Azzi Abdelmalek 2014년 3월 26일
%example
a.b=1
a.c=2
a.d=3
%----------------
f=fields(a)
for k=1:numel(f)
a.(f{k})=[];
end
  댓글 수: 1
Karl
Karl 2014년 3월 26일
편집: Karl 2014년 3월 26일
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?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by