MATLAB: Help me to solve this

computer visionimage processing

I am very new to matlab and working on image processing in order to detect the object.
I have an Index matrix I: 10 11 12 13 14 15 16 20 21 22 23 24 26 29 30 31 32 37 39 40 Highestvalue, H=13
M=[]; % THIS IS NOT THE FULL CODE
for i=1
for j=1:ILength
if((Distance(H,I(j))<=10)&& (adjMatrix(H,I(j))~=0))
M=[M,j];
end
end
end
I got the result like this: "Result" or M for H 13= 12,13,14.
Expected result is "12 13 14 15 16 20 21 22 23 24 26 29 30 31 32"
Question: How to perform it again for each and every value in the "Result" with no repetitions? For example, again I need to calculate adjacency and distance for 14,12. (For 14, the expected value is 15,16,20) and then for 16, 20 and so on.
Thanks in advance

Best Answer

You can solve the problem by introducing the array "usedIndices" which collects all values of H that have been used. "newIndices" are values that are contained in M, but have not been used yet.
M=[];
usedIndices=[];
newIndices=[13];
while ~isempty(newIndices)
for i=length(newIndices)
H=newIndices(i);
for j=1:length(I)
if((Distance(H,I(j))<=10)&& (adjMatrix(H,I(j))~=0))
M=[M,I(j)];
end
end
M = unique(M);
usedIndices = [usedIndices, H];
end
newIndices = setdiff(M,usedIndices);
end
Which indeed yields:
M = [12,13,14,15,16,20,21,22,23,24,26,30,31,32]