I have a vector set as follows:
S = { [14, 2, 11, 10, 3, 8, 7, 1], [15, 4, 8, 7, 1], [16, 5, 4, 8, 7, 1] };
For example, S{1} means that there exists edges between (14,2), (2,11), (11,10), (10,3), (3,8), (8,7), (7,1).
I want to make an adjacency matrix based on S. My code is as follows:
N = 20;
A = zeros(N);
for i=1:length(S)
for j=1:length(S{i})-1
from = S{i}(j);
to = S{i}(j+1);
A(from, to) = 1;
A(to, from) = 1;
end
end
Is there a function working like my code? I think the existing code is much faster than my C-code-like code.
I'm not familiar with a function for creating an adjacency matrix without first constructing a graph. If you're just looking for a faster implementation then the following might work for you. For small problems like the one you posted it doesn't work any faster, but for big problems it seems to be about 4-5 times faster.
A = zeros(N);
for idx=1:numel(S)
s = S{idx};
from = s(1:end-1);
to = s(2:end);
A(([to from]-1)*N+[from to]) = 1;
end
Here's the big example problem I created for testing purposes.
N = 1000;
S = cell(1,1000);
for idx = 1:numel(S)
r = randperm(N);
S{idx} = r;
end
Timing difference using MATLAB2017a:
Your method: 0.149983 seconds.
This method: 0.036491 seconds.