简体   繁体   中英

matlab - Accumarray Adjacency Matrix Confusion?

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!

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM