# List of neighbors from adjacency matrix

2 views (last 30 days)
Abhishek Varghese on 14 Feb 2018
Commented: Steven Lord on 1 Mar 2018
Hi everyone,
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 on 14 Feb 2018
Edited: Matt J on 14 Feb 2018
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
Nitika Kandhari on 1 Mar 2018
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 on 1 Mar 2018
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.