How to scan through several structures in MATLAB?

混江龙づ霸主 提交于 2019-12-11 15:11:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!