2017-04-26 195 views
0
pond_matriz<-matrix(c(0,17.6,18.3,9.1,6.1,12.3,4.5,9.4, 
      + 0,0,173.4,10.6,5.4,20.3,4.0,9.9, 
      + 0,149.4,0,10.9,5.3,22.5,3.7,10.2, 
      + 0,6.9,8.3,0,6.2,14.5,3.9,17.8, 
      + 0,4.2,4.7,7.3,0,5.3,14.4,13.4, 
      + 0,14.9,19.3,16.3,5.3,0,3.4,11.5, 
      + 0,4.4,4.8,6.5,21.7,5.3,0,10.8, 
      + 0,3.2,3.8,9.0,5.7,5.1,3.1,0),nrow=8, byrow=T) 

pond0<-pond_matriz[1,] 
pond1<-pond_matriz[2,] 
pond2<-pond_matriz[3,] 
pond3<-pond_matriz[4,] 
pond4<-pond_matriz[5,] 
pond5<-pond_matriz[6,] 
pond6<-pond_matriz[7,] 
pond7<-pond_matriz[8,] 

f1<- function(line,cost,k){ #cost is not used yet 

if(k!=0){ 
# is.integer(k) 
    new_line<-line[-c(k)] 
    pos<-(which.is.max(pond1)-1) 
    cat("go to position",pos,"\n") 

} 
    if(k==0){ 
    pos<-(which.is.max(line)-1) 
    cat("go to position",pos,"\n") 
    } 

} 

當我想從位置0(pond0)去時,R - 從矩陣中獲取向量中最大值的位置

> g<-c(0) # I dont want to go from 0 to 0 
    > f1(pond0,0,g) 
    go to position 2 #18.3 

> pond0 
[1] 0.0 17.6 **18.3** 9.1 6.1 12.3 4.5 9.4 

在這裏它很好,那麼我做;

> g<-c(0) #Dont want to return yet to position 0 
> f1(pond2,0,g) 
go to position 1 #149.4 

> pond2 
[1] 0.0 **149.4** 0.0 10.9 5.3 22.5 3.7 10.2 

這裏,它太好了,

> g<-c(3) #pos2 
> f1(pond1,0,g) 
go to position 4 

> pond1 
[1] 0.0 0.0 *173.4* 10.6 5.4 **20.3** 4.0 9.9 

這裏是我的問題,我知道,我說的刪除173.4,但我只想說POS2不考慮,因爲我已經來過了,我想知道我該怎麼做才能說「去第5個位置「。我怎麼能認爲,20.3(原因是173.4和POS2我曾到過那)是最大的不改變他的立場

回答

1

肯定有一個更好的辦法來做到這一點,但你的代碼這一項工作:

f1<- function(line,cost,k){ #cost is not used yet 

    if(k!=0){ 
    # is.integer(k) 

    new_line<-c(rep(NA,k),line[(k+1):length(line)]) 


    pos<-(which.max(new_line)-1) 
    cat("go to position",pos,"\n") 
} 
    if(k==0){ 
    pos<-(which.max(line)-1) 
    cat("go to position",pos,"\n") 

    } 

} 

NEW_LINE現在是你想要不失剩餘值的位置跳過位置NA值向量

您的例子,結果如下:

> g<-c(0) 
> f1(pond0,0,g) 
go to position 2 
> pond0 
[1] 0.0 17.6 **18.3** 9.1 6.1 12.3 4.5 9.4 
>  
> g<-c(0) 
> f1(pond2,0,g) 
go to position 1 
> pond2 
[1] 0.0 **149.4** 0.0 10.9 5.3 22.5 3.7 10.2 
>  
> g<-c(3) 
> f1(pond1,0,g) 
go to position 5 
> pond1 
[1] 0.0 0.0 173.4 10.6 5.4 **20.3** 4.0 9.9 

我已經切換到基礎包中的which.max函數,因爲我沒有得到您使用的那個函數。

希望它可以幫助你!