MATLAB Answers

Storing the positions of neighbouring elements that have specific values.

2 views (last 30 days)
Phillip Smith
Phillip Smith on 27 Nov 2019
Commented: Phillip Smith on 27 Nov 2019
A = zeros(5,5);
A(3,4)=1;
A(4,1)=1
I have a matrix of zeros with two 1's in postions (3,4) and (4,1). Starting with the 1 at (3,4) I want to store all the positions of neighbouring elements that are eqaul to 0. I want to do this as my next step is to choose one of the neighbours that equal 0, change that to a 1, and then start the whole process again, starting at any element that equals 1.

  0 Comments

Sign in to comment.

Accepted Answer

dpb
dpb on 27 Nov 2019
>> i0=3; j0=4;
>> [i,j]=find(~A(i0-1:i0+1,j0-1:j0+1));
>> [i,j]
ans =
1.00 1.00
2.00 1.00
3.00 1.00
1.00 2.00
3.00 2.00
1.00 3.00
2.00 3.00
3.00 3.00
>>
You'll have to restrict search to either include only interior initial points or modify to account for location on boundary in computing range vectors.

  3 Comments

Phillip Smith
Phillip Smith on 27 Nov 2019
Okay that works but the indices are all relative to the initial point, I would like to have the postions relative to the whole matrix. Since it starts at 3,4 the output should give me the positions 2,3 2,4 ,2,5 3,3 3,5 4,3 4,4 4,5 right?
dpb
dpb on 27 Nov 2019
Just add the initial position offset less one for one-based counting (twice)...
>> [i+i0,j+j0]-2
ans =
2.00 3.00
3.00 3.00
4.00 3.00
2.00 4.00
4.00 4.00
2.00 5.00
3.00 5.00
4.00 5.00
>>
Phillip Smith
Phillip Smith on 27 Nov 2019
I did this and has worked perfectly
[r,c]=find(~D(i:i+2,j:j+2));
E=[r,c];
n=length(E);
for k=1:n
for x=1:2
if E(k,x)==1
E(k,x)=-1;
elseif E(k,x)==2
E(k,x)=0;
elseif E(k,x)==3
E(k,x)=+1;
end
end
end
Y= E+[i j];
where D is just the matrix that i am using and i,j is the initial point!!

Sign in to comment.

More Answers (0)

Sign in to answer this question.