MATLAB: How to make a code with for loop for undetermined index

matlab undetermined index

Hi all,
I have a code in GO ontology that it build the part of tree (POT) by finding each level for each cell (which called nodes in bioinformatic) in cells array .. The code is manual( I have already know the number of levels and te data entered). I want to make this code work with undetermined number of levels and data (vector 'p' and 'c' as you will see bellow). note that the first level should be a single value ( because it should be the root level), so that from this root level we have to find level 2 , and from level 2 we have to find level 3 and so on…
so, I want the conclusion code to find the following: finding all nodes for each level and put them all in a vector ( or cells array) called levels as follows: levels=[ level1 level2 level3….leveln] and each level contain the terms it belongs to ( according to the following code)such as:
level1=['node1' 'node2' 'node3'.. etc]
part of the code is:
% this code is to find levels for the cells array 'p' and 'c' (resulted from % previous code
%to find the root (level 1)
level1_root=setdiff(p,c)
% to find level 2
level2=[];
for i=1:length(p)
a=[p(i),c(i)];
if isequal(a(1), level1_root)
level2=[level2 a(2)];
else
end
end
% to find level 3
level3=[];
for j=1:length(level2)
for i=1:length(p)
a=[p(i),c(i)];
if isequal(a(1), level2(j))
level3=[level3 a(2)];
else
end
end
end
% to find level4
level4=[];
for j=1:length(level3)
for i=1:length(p)
a=[p(i),c(i)];
if strcmp(a{1}, level3{j})
level4=[level4 a(2)];
else
end
end
end
can I use while loop? is so, how?!
thx alot

Best Answer

save this function
function level=level_fc(p,c,level1)
level=[];
for i=1:length(p)
a=[p(i),c(i)];
if isequal(a(1), level1)
level=[level a(2)];
end
end
then call your function
level1=level1_root
for k=1:10
level{k}=level_fc(p,c,level1)
level1=level{k}
end
Related Question