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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by