-1

i am a new user of matlab and need help in creating adjacency matrix from a data set. dataset is in the following pattern

A=[   
0 1    
0 2    
0 5    
1 2    
1 3    
1 4    
2 3    
2 5    
3 1    
3 4    
3 5    
4 0    
4 2    
5 2    
5 4    
];

the adjacency matrix for above will be

M=    0 1 1 0 0 1
      0 0 1 1 1 0
      0 0 0 1 0 1
      0 1 0 0 1 1
      1 0 1 0 0 0
      0 0 1 0 1 0

i need code to perform the above task in matlab

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
Usman Raza
  • 13
  • 1
  • 3
  • Please show your effort. No homework please – Ankur Aggarwal Sep 10 '14 at 18:37
  • 1
    This is actually a problem of [how to modify values of a matrix in known positions](http://stackoverflow.com/questions/12294232/changing-multiple-elements-of-known-coordinates-of-a-matrix-without-a-for-loop). It doesn't really involve adjacency... – Dev-iL Sep 10 '14 at 19:19

3 Answers3

1

Welcome to SO! Please read the following guide on how to ask good questions.

To elaborate on @Ankur's comment, please also take a look at this Open letter to students with homework problems: "...If your question is just a copy paste of homework problem, expect it to be downvoted, closed, and deleted - potentially in quite short order."


What you need to do is pretty straight-forward:

  1. First you preallocate your M matrix, using either M=zeros(6); or M(6,6)=0; (this option assumes M does not exist).
  2. Next thing you should note is that MATLAB uses "1-based indexing", which means that you can't use the indices in A as-is and you first need to increment them by 1.
  3. After incrementing the indices, we see that "A+1" contains the coordinates of M that should have a 1 in them (I noticed that the adjacency matrix is asymmetric in your case). From here it's a matter of accessing the correct cells, and this can be done using sub2ind(...).

Finally, the code to generate M is:

M=zeros(6);
M(sub2ind(size(M), A(:,1)+1, A(:,2)+1))=1;
Community
  • 1
  • 1
Dev-iL
  • 23,742
  • 7
  • 57
  • 99
1

You could use sparse. Please take a look at that function, give your problem a try, and then check by hovering the mouse over the following rectangle:

full(sparse(A(:,1)+1, A(:,2)+1, 1))

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0

I don't understand your matrix A, but supposing that A is of the same dimensions as the sought adjacency matrix M, and that you simply want to keep all the zero entries as "0", but want to make the positive entries equal to "1", then just do:

M = (A>0)

As pointed out in a comment by @Dev-iL above, this is a "problem of how to modify values of a matrix in known positions. It doesn't really involve adjacency..."

Seb
  • 165
  • 9