Filter löschen
Filter löschen

How to find the neighbors of each element in a matrix

50 Ansichten (letzte 30 Tage)
Saou
Saou am 23 Mai 2018
Kommentiert: Dyuman Joshi am 11 Aug. 2024
Hi,
how I can find the neighbors of each element in a given matrix? Does such a method exist in Matlab?
Here is an example : A=[3 4 8 6; 1 6 9 0; 2 5 7 1]
The neighbors of A(1,1) are {1, 4, 6}; The neighbors of A(1,2) are {3, 1, 6, 8, 9}; The neighbors of A(2, 1) are {3, 2, 4, 6, 5}; The neighbors of A(2, 2) are {3, 1, 2, 4, 5, 8, 9, 7}
Thanks.
  1 Kommentar
Mitulkumar Vasani
Mitulkumar Vasani am 17 Mär. 2021
Verschoben: Dyuman Joshi am 11 Aug. 2024
i have quation regarding finde neighbors for vector
ex. A=[-20 -15 -12 -10 -5 - 3 0 1 2 5 6 8 10]
if i need a to find nearest neighbors for (3)
then as answer will come as 2 and 5
is there any code in matlab?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 23 Mai 2018
Bearbeitet: Stephen23 am 23 Mai 2018
Here is a simple method using conv2:
>> A = [3,4,8,6;1,6,9,0;2,5,7,1];
>> M = zeros(size(A));
>> M(1,1) = 1; % location
>> A(conv2(M,[1,1,1;1,0,1;1,1,1],'same')>0)
ans =
1
4
6
>> M(:) = 0;
>> M(1,2) = 1; % location
>> A(conv2(M,[1,1,1;1,0,1;1,1,1],'same')>0)
ans =
3
1
6
8
9
>> M(:) = 0;
>> M(2,1) = 1; % location
>> A(conv2(M,[1,1,1;1,0,1;1,1,1],'same')>0)
ans =
3
2
4
6
5
>> M(:) = 0;
>> M(2,2) = 1; % location
>> A(conv2(M,[1,1,1;1,0,1;1,1,1],'same')>0)
ans =
3
1
2
4
5
8
9
7
  2 Kommentare
Dyuman Joshi
Dyuman Joshi am 11 Aug. 2024
I have accepted Stephen's answer as it solves the problem with clarity.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Andrei Bobrov
Andrei Bobrov am 23 Mai 2018
Bearbeitet: Andrei Bobrov am 23 Mai 2018
s = size(A);
B = zeros(s);
n = numel(A);
out = cell(s);
for ii = 1:n
B(ii) = 1;
out{ii} = A(bwdist(B,'ch') == 1);
B(ii) = 0;
end

KSSV
KSSV am 23 Mai 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by