我會去一個簡單的循環:
# initialize your matrix with all zeros
m <- matrix(0,nrow=vcount(g),ncol=vcount(g)+1)
# iterate over elements of k
for(fromVertex in 1:length(k)){
# iterate over res entry of each element of k
for(path in k[[fromVertex]]$res){
# path is a vertex sequence, same type as V(g),
# calling as.integer we get the vertices indexes inside the sequence
verticesOfPath <- as.integer(path)
# we exclude the first and the last vertex (from,to)
innerVertices <- verticesOfPath[c(-1,-length(verticesOfPath))]
if(length(innerVertices) > 0){
# this is not a direct path
m[verticesOfPath[1],innerVertices] <- m[verticesOfPath[1],innerVertices] + 1
}
# add 1 to the last column
m[verticesOfPath[1],ncol(m)] <- m[verticesOfPath[1],ncol(m)] + 1
}
}
結果:
> m
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
[1,] 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1
[2,] 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1
[3,] 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1
[4,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
[5,] 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 2
[6,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
[7,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
[8,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
[9,] 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 2
[10,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
[11,] 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1
[12,] 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1
[13,] 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1
[14,] 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1
[15,] 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1
如果頂點具有名稱屬性,你可以將它們設置爲矩陣的行和col名稱:
rownames(m) <- V(g)$name
colnames(m) <- c(V(g)$name,'TOT')
> m
A B C D E F G H I J K L M N O TOT
A 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1
B 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1
C 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1
D 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
E 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 2
F 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
G 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
H 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
I 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 2
J 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
K 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1
L 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1
M 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1
N 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1
O 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1
這肯定會有所幫助,在CAS e我的頂點被命名,是否有矩陣保留頂點標籤而不是1,2,3,....我正在計算這些值爲許多網絡,所以想要一種方式來跟蹤 – dimebucker91
@ dimebucker91:檢查我的編輯;) – digEmAll
真棒!謝謝 - 最後一件事(我可以修正)你稱之爲'直接'的列實際上是要計算從節點i到節點7的所有最短路徑,例如,直接矢量的第一個元素應該是1,因爲我們有一個路徑A> D> 7 – dimebucker91