How to create a weighted adjacency matrix from an Nx2 matrix?

1 view (last 30 days)
Hi,
I have an Nx2 matrix in which the 1st column only has a few distinct elements (which I want as the nodes in my adjacency matrix) and the values of the adjacency matrix should be the number of values that are same for the two nodes in consideration which in turn is determined by values in column 2 of the Nx2 matrix. An example: [0 A; 0 B; 0 C; 0 D; 1 A; 1 C; 1 D]
So I want an adjacency matrix which is like: [0 3; 0 0] -> 3 because A,C and D are common to both 0 and 1 nodes
I tried this: http://mathforum.org/kb/message.jspa?messageID=8887417 but it only works if the relationship between the nodes is already known which in my case has to be calculated from column 2.
Is there any way to do it in Matlab?
Thanks in advance.

Answers (2)

NISARGA G K
NISARGA G K on 12 Feb 2018
Hi Nisarg,
I understand that you have an N-by-2 matrix with nodes in 1st column and want to create an adjacency matrix with its values to be number of values that are same for two nodes in consideration.
You can take the following code snippet as a reference to accomplish the same:
x={0,'A';0,'B';0,'C';0,'D';1,'A';1,'C';1,'D'};
%get nodes and values in two separate arrays
nodes=cell2mat(x(:,1));
val=cell2mat(x(:,2));
%create adjacency matrix
r=zeros(2);
i=1;
%get index of nodes with similar values
%increment corresponding values in adjacency matrix
while nodes(i)==0
k=nodes(val(i)==val)
if(length(k)==2)
r(k(1)+1,k(2)+1)=r(k(1)+1,k(2)+1)+1
end
i=i+1;
end

Walter Roberson
Walter Roberson on 12 Feb 2018
unique() the matrix and take the third output. This will convert the arbitrary labels in the array (which might not even be numeric or integer) into class numbers. Do not unique by row, let it unique the whole thing. The third output should be an Nx2 matrix. Now put that third output in Nx2 form into accumarray as the subs, with val (second parameter) as 1. The result will be counts of the number of times the link occurred.
Now find() on the accumarray using the three output form of find,getting out row and column and count. Then pass the three vectors into graph() as the s and t and weights. You might want to also use the first output from unique() as the labels for the graph.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!