List of neighbors from adjacency matrix

6 ビュー (過去 30 日間)
Abhishek Varghese
Abhishek Varghese 2018 年 2 月 14 日
コメント済み: Steven Lord 2018 年 3 月 1 日
Hi everyone,
I have an adjacency matrix:
0 1 1 1
1 0 0 1
1 0 0 1
1 1 1 0
I'm trying to create an array that will list the neighbours of each node. Such that I have an output:
[1] 2,3,4
[2] 1,4
[3] 1,4
[4] 1,2,3
An efficient and fast way to compute this would be much appreciated. Cheers.

採用された回答

Matt J
Matt J 2018 年 2 月 14 日
編集済み: Matt J 2018 年 2 月 14 日
yourMatrix=[0 1 1 1
1 0 0 1
1 0 0 1
1 1 1 0];
[i,j]=find(yourMatrix);
result = accumarray(i,j,[size(yourMatrix,1), 1],@(x) {sort(x).'});
>> result{:}
ans =
2 3 4
ans =
1 4
ans =
1 4
ans =
1 2 3
  6 件のコメント
Nitika Kandhari
Nitika Kandhari 2018 年 3 月 1 日
I tried this:
for i = 1:length(result)
output(i,:)= cellstr(num2str(result{i,1}));
end
and I got 5 X 1 matrix as output:
'1 2'
'3 4 5 6 7'
'8 9 10 11 12 13 14 15 16'
'17 18 19 20 21 22 23 24 29 30 38 39 40 46'
'47 48 49 55 56 61 67 93 94 95 96'
Steven Lord
Steven Lord 2018 年 3 月 1 日
You can't have a matrix in MATLAB where one row has 3 columns and another has 2 columns. You could try padding the shorter rows with missing data using either missing or NaN or padding with 0, but depending on what you want to do with this information it may be simpler just to use the cell array Matt's code creates.
If you tell us what you would do with such a neighbors matrix, we may be able to offer suggestions that will make your later processing easier.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by