How to choose neighbors in MATLAB

1 回表示 (過去 30 日間)
charu shree 2023 年 5 月 14 日
コメント済み: charu shree 2023 年 5 月 15 日
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 2023 年 5 月 14 日
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.
1 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
charu shree 2023 年 5 月 15 日

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStatistics and Machine Learning Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by