我有一个结构,结果如下:
result.me={dad,grandpa,half_sis} result.step_mom={half_sis} result.dad={me,grandpa,half_sis} result.half_sis={mom,me,dad,grandpa} result.grandpa={me,dad,half_sis}
结果是一个单元格数组的结构,并显示每个元素的亲属(按血统)。我编写了以下函数,它采用相应的 class_name(me、mom 等)及其相应的单元格并返回所有亲属。例如, recur_getchildren(mom,{grandpa,me,sis},result) 应该返回 mom 的所有血缘亲属以及所有这些亲属的亲属(依此类推,直到没有人离开):
ans=half_sis,我,爸爸,爷爷,
所以即使妈妈和我、爸爸或爷爷没有血缘关系,他们仍然会被列出来。上面的例子是一个简化,对于我的问题,将会有更多的世代需要跟踪。我尝试执行以下操作,但它并不完全有效。我究竟做错了什么?有没有更简单的方法来做到这一点?
function tot=recur_getchildren(class_name,each_cell,result)
%gets all the children for an element and all its descendants
global gresult
if(~isfield(gresult,class_name))
gresult.(class_name)=1;
w=size(each_cell,2);
tot=struct(char(class_name),1); %include the class_name item as well
%tot is a struct where all the keys indicate the progeny, and val is 0/1
for m=1:w
%the child must not have already been searched previously
if(~isfield(gresult,each_cell{m}))
gresult.(char(each_cell{m}))=1;
tot.(char(each_cell{m}))=1;
% copy all contents over to parent
if(sum(~strcmp(each_cell,'')) && sum(isfield(result,char(each_cell{m}))))
s=size(result.(char(each_cell{m})),2);
%run iteratively over all the children of each member of
%each_cell
for j=1:s
%struct of all childs
%gresult.(each_cell{m})=1;
if(~isfield(gresult,char(result.(char(each_cell{m})){j})))
tot.(char(result.(char(each_cell{m})){j}))=1;
% tot_records.(char(result.(char(each_cell{m})){j}))=1
tot2=recur_getchildren(each_cell{m},result.(char(each_cell{m}))(j),result);
%check off this so that we dont search it again
gresult.(char(result.(char(each_cell{m})){j}))=1;
%keep looping to get all children
%loop through result struct
if(size(tot2,2)~=0)
fn=fieldnames(tot2);
for p=1:size(fn)
str=fn(p);
recur_getchildren(char(str),result.(char(str)),result)
gresult.(char(str))=1;
end
end
end
end
end
end
end
else
tot=[];
end
end