问题
I have some structure arrays (like structure1, structure2, structure3,...) with similar field names. I want to scan through all the structures and return only those whose first field is 5 (Field1==5). I have this code so far,
for k=1:3
s=sprintf('Structure%d',k)
Structure=load(s)
idx=cellfun(@(x) x==5, {Structure.Field1})
out=Structure(idx)
v{k}={Structure.Field1}
end
but it gives me this error:
Reference to non-existent field 'Field1'.
Can someone please point out whats wrong here?
Thanx
回答1:
for k=1:3
s=sprintf('Structure%d',k)
Structure=load(s)
eval(['newStructure(k)=Structure.' s]);
idx(k)=cellfun(@(x) x==5, {newStructure(k).Field1})
end
%extract the structures from newStructure which have 1 in idx
out=newStructure(idx); %idx should be a logical array
for i=1:size(out,2)
v(i)=out(i).Field1;
end
This should work perfectly.
回答2:
It appears as if some of your saved structures do not have 'Field1'
as a field in them.
In that case, you might want to try something else.
First define a function (in m-file)
function res = iff( cond, true_case, false_case )
%
% conditional execution of two function handles
%
% true_case and false_case are function handles expecting no inputs
%
if cond
res = true_case();
else
res = false_case();
end
Once you have this function you can use it in the cellfun
idx = cellfun( @(x) iff( isfield(x, 'Field1'), @() x.Field1 == 5, @() false), Structure );
来源:https://stackoverflow.com/questions/15050003/how-to-scan-through-several-structures-in-matlab