# How to choose neighbors in MATLAB

1 view (last 30 days)
charu shree on 14 May 2023
Commented: charu shree on 15 May 2023
Hello all, I am dealing with following Graph. Here I had found out neighbors of node 'i' and 'j' as below:
sr = [1,2,2,2,2,3,3,3,3,4,4,5,6,6,6,7]; % various possible Source
ta = [2,1,3,6,8,2,4,6,7,3,6,6,3,4,5,3]; % various possible Targets
G = graph(sr,ta); % models the Graph
for m = 1:length(sr)
i = sr(m);
j = ta(m);
k1 = (neighbors(G,i))'; % neighbors of node 'i'
k2 = (neighbors(G,j))'; % neighbors of node 'j'
end
My query is how can we include these neighbors k1, k2 such that their values is not equal to i and j. Any help in this regard will be highly appreciated.

Shaik on 14 May 2023
Hi Charu Shree garu,
To include the neighbors k1 and k2 such that their values are not equal to i and j, you can modify your code as follows:
sr = [1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, 6, 6, 7]; % Source nodes
ta = [2, 1, 3, 6, 8, 2, 4, 6, 7, 3, 6, 6, 3, 4, 5, 3]; % Target nodes
G = graph(sr, ta); % Create the graph
for m = 1:length(sr)
i = sr(m);
j = ta(m);
k1 = neighbors(G, i)'; % Neighbors of node 'i'
k1 = k1(k1 ~= i); % Remove 'i' from the list of neighbors
k2 = neighbors(G, j)'; % Neighbors of node 'j'
k2 = k2(k2 ~= j); % Remove 'j' from the list of neighbors
end
In this code, after obtaining the neighbors k1 and k2, we filter out the values equal to i and j using logical indexing. The expression k1 ~= i returns a logical array with true where the values are not equal to i, and false where the values are equal to i. We then use this logical array to index k1 and select only the elements that satisfy the condition.
The same logic applies to k2 as well.
With these modifications, the variables k1 and k2 will only contain the neighbors that are not equal to i and j.
Note that this code assumes that sr and ta are column vectors representing the source and target nodes respectively.
charu shree on 15 May 2023