1

So I'm trying to create an adjacency matrix, and I'm confused on the difference between accumarray(matrix+1,1) and accumarray(matrix,1).

I did:

matrix = [ 1 3 
           4 2 
           1 3 
           3 1]

adMatrix1 = accumarray(matrix,1);
adMatrix1=adMatrix1~=0; 
adMatrix1 = [0 0 1  
             0 0 0  
             1 0 0  
             0 1 0]

and then:

adMatrix2 = accumarray(matrix+1,1); 
adMatrix2=adMatrix2~=0;
adMatrix2 = [0 0 0 0 
             0 0 0 1
             0 0 0 0 
             0 1 0 0 
             0 0 1 0]

I know that with the "matrix+1", there's an extra row and column of zero's, but I don't understand why you would do it that way. When I looked it up, according to this post I should use "matrix+1", and the best explanation that I got for that was that "because indexing in matlab starts at 1".

I don't understand that at all... if I was trying to create an adjacency matrix, which way is correct? Any help would be greatly appreciated, thanks!

ocean800
  • 3,489
  • 13
  • 41
  • 73

2 Answers2

3

If your node IDs are 0 indexed you need the +1, otherwise you don't. So the question you need to ask is, are your node IDs 0 indexed or 1 indexed?

hiandbaii
  • 1,276
  • 8
  • 14
  • Oh my nodeID's are indexed starting from 1, so then I think the `accumarray(matrix,1)` should be the right one, thanks! – ocean800 May 19 '15 at 20:52
1

Does your matrix accept multiple links? If yes, then both results with accumarray above are not correct, since node 1 and 3 are connected 2 times.

Btw, you can consider sparse and full:

full(sparse(matrix(:,1), matrix(:,2), ones(1, size(matrix, 1))))

ans =

 0     0     2
 0     0     0
 1     0     0
 0     1     0

ones(1, size(matrix, 1)) is actually a vector of weight.

scmg
  • 1,904
  • 1
  • 15
  • 24
  • 1
    thanks for pointing the multiple links, but when I call just `adMatrix1 = accumarray(matrix,1);` without the `adMatrix1=adMatrix1~=0;` I do get a adjacency matrix with multiple links, I just don't want those shown in the final matrix. Also, thanks for the explanation for `full`, `sparse`, and `ones`! – ocean800 May 19 '15 at 21:17
  • 1
    oh sorry, i didnt notice the logical command, just saw the results hehe – scmg May 19 '15 at 21:29