Performing Action to ALL 'struct' Variables

조회 수: 4 (최근 30일)
Philip
Philip 2011년 5월 19일
편집: per isakson 2018년 2월 25일
Is there a way to perform the same action on several variables of type 'struct'?
In my case, I have 30 separate 'struct' variables (with non-logical names), and each of them contains a single vector of 200 elements. I only want to deal with the second half of these elements so I need something like:
struct_name = struct_name.data(100:end)
But need to keep the name of the struct variable intact. Does anyone have any suggestions?
I hope this made sense!

채택된 답변

Matt Fig
Matt Fig 2011년 5월 19일
% Create several structures with different names...
structn.dat = 1:10;
structm.dat = 1:10;
structk.dat = 1:10;
% Now edit the data.
save mystructs structn structm structk
X = load('mystructs');
F = fieldnames(X);
for ii = 1:length(F)
X.(F{ii}).dat = X.(F{ii}).dat(5:10);
end
% Check
X.structm.dat
  댓글 수: 8
Philip
Philip 2011년 5월 19일
Perfect - thanks for your help!! Now to work out how to get just the last 100 elements for each!
Thanks again!
Walter Roberson
Walter Roberson 2011년 5월 19일
편집: per isakson 2018년 2월 25일
SFN = fieldnames(MyStruct);
for K = 1 : length(SFN)
var_name = SFN{K};
VFN = fieldnames(MyStruct.(var_name));
for N = 1 : length(VFN)
this_field = VFN{N};
if isvector(MyStruct.(var_name).(this_field)) & ...
length(MyStruct.(var_name).(this_field)) > 100
MyStruct.(var_name).(this_field) = MyStruct.(var_name).(this_field)(1:100);
end
end
end

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

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2011년 5월 19일
Would this help?
a(200).b=1;
a(200).c=0;
NewStruct=a(100:end);
Or, Do you mean keep the struct variable name, not the field names:
a(1:99)=[];
Now I think you mean this:
a.Data=1:200;
a.Data(1:100)=[]
  댓글 수: 1
Philip
Philip 2011년 5월 19일
Apologies - I feared I wasn't very clear.
I meant to say that I have 30 separate variables (of type 'struct'), and each of these has a different name (i.e. fh, cy, de, it etc..). Now, instead of each of them containing 200 elements, I want to 'update' each of them so that they each contain only the last 100.

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

카테고리

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