我最近创建了此代码,并且在为for循环运行的过程中遇到了麻烦。如果我尝试运行此代码,R似乎要花很多时间,而且我不确定错误在哪里:
Graph <- rbind(c(0,0.8,0,0.2,0.1),
c(0,0,0.7,0.6,0.1),
c(0,0,0,0,0.9),
c(0,0,0,0,0.2),
c(0,0,0,0,0))
AmountNodes<-5
Method<-"unweighted"
InfectedNodes<-c(1)
## Function Amount Excluded
SIR_algorithm<-function(Graph, AmountNodes, Method){
ResultMatrix <- rep(0, AmountNodes)
as.data.frame(ResultMatrix)
if (strcmp(Method,"unweighted")){
Graph <- sign(Graph)}
for (i in 1:AmountNodes){
InfectedNodes <- rep(AmountNodes, 0)
ExcludedNodes <- rep(AmountNodes, 0)
InfectedNodes <-c(1)} # Initial Infection, k=Columns, j=Rows
while(sum(InfectedNodes) > 0){
InfectedNodes_Reflection <- InfectedNodes
for (j in 1:nrow(Graph)){
if (Graph[j] == 1){
for (k in 1:ncol(Graph)){
if ((Graph[k,j] > 0 && (InfectedNodes[k][1]) == 0 && (ExcludedNodes[k][1]) == 0)){
RandomValue <- runif(1, max=1, min=0)
if (RandomValue < (Graph[k,j])){
InfectedNodes_Reflection[k] <- k == 1
} #End If-Function
} #End If-Function
} #End For-Function k
} #End If-Function
}} #End For-Function j
for (j in 1:AmountNodes){
if (InfectedNodes[j] == 1){
InfectedNodes[j] <- c(0)
InfectedNodes_Reflection[j] <- c(0)
ExcludedNodes[j] <- c(1)}} #End If-Function and for-function
InfectedNodes <- InfectedNodes_Reflection
ResultMatrix[i] <- ExcludedNodes
length(ResultMatrix) #check length for ResultMatrix
length(ExcludedNodes) #check length for ExcludedNodes
} #End While-Function
#End For-Function i
AmountExcluded <- sum(ResultMatrix)/AmountNodes
#Damage Values<- ResultMatrix * Damage Potential
} #End Function_total
SIR_algorithm(Graph=Graph,AmountNodes=5,Method="unweighted")
有人可以帮我吗?
答案 0 :(得分:0)
问题位于以下几行:
...
while(sum(InfectedNodes) > 0){
print(sum(InfectedNodes))
InfectedNodes_Reflection <- InfectedNodes
...
sum(InfectedNodes)
是常数,等于1
。因此循环是无限的。