矩阵中的最小成本距离

时间:2018-11-02 15:17:42

标签: r matrix knn dtw

我在下面有这个矩阵

k
   [,1]  [,2]  [,3] ,4][,5] [,6]
 [1,] 1    4    9   16   25   36
 [2,] 1    3    7   13   21   31
 [3,] 2    2    5   10   17   26
 [4,] 4    2    4    8   14   22
 [5,] 7    3    3    6   11   18
 [6,] 11    5    3    5    9   15

,我想循环从k[1,1]开始到k[6,6]结束。我的循环条件基于min(k[i,j+1], k[i+1,j], k[i+1, j+1]),我希望得到的答案类似于1+1+2+2+3+3+5+9+15 = 41(沿着最小路径游走)

几乎可以计算出从k[1,1]开始的最小值,然后一直向下直到k[6,6]

warpingDist = function(x, y, z){
mincal = numeric(length(k))
m = nrow(k)
n = ncol(k)
i=1
j=1
mincal = which(k == min(k[i, j+1], k[i+1, j], k[i+1, j+1]), arr.ind = TRUE)
indx = data.frame(mincal)
i= indx$row
j= indx$col
if(i != m || j!=n)
{
warpingDist(k[i, j+1], k[i+1, j], k[i+1, j+1])
}

warpSum = sum(mincal)
return(warpSum)
}
value = apply(k, c(1,2), warpingDist)
value

当我运行此代码时,它显示以下内容:

Error: object 'value' not found

不确定为什么会这样...

2 个答案:

答案 0 :(得分:1)

由于您没有提供最小的可复制示例,我只能猜测:

warpingDist = function(x, y, z, k){
# browser() # This is a good option to activate, if you run your script in RStudio
...
return(warpSum)
}

# your code
k <- whatever it is
result <- warpingDist(x, y, z, k)

我希望有帮助。

答案 1 :(得分:0)

很高兴,我终于能够解决问题了……代码也运行得很快

问题:查找矩阵的最低成本。为了清楚起见,假设我具有下面给出的矩阵:

[1,]    1    4    6    7    8    9    0
[2,]   10   12    1    3   11    2    0
[3,]   11   12    2    8   17    1    0
[4,]   20    1   18    4   28    1    0
[5,]    5   20   80    6    9    3    0

我的目标是增加从kata [1,1]第一行到最后一行K [5,4]的最小路径距离。如此有效,我想拥有1 + 4 + 1 + 2 + 4 + 6 + 9 + 3之类的东西。

下面是我用来实现此目标的R代码。它实现了两个功能:

# Function that  calculates minimum of three values. Returns the Value.

minFUN <- function(Data, a, b){
d =  (min(Data[a, b+1], Data[a+1, b], Data[a+1, b+1]))
return(d)
       }
# Function that calculates the index of the minimum value, from which the
# The next iteration begins 
NextRC <- function(Data, a, b){
 d = min(Data[a, b+1], Data[a+1, b], Data[a+1, b+1])
     if(d == Data[a, b+1]){
         c = cbind(a, b+1)
         }else
 if(d == Data[a+1, b]){
         c = cbind(a+1, b)
    } else
 if(d == Data[a+1, b+1]){
         c = cbind(a+1, b+1)
        }

return(c)
}

Je <- c()
NewRow = 1
NewCol = 1
# Warping Function that uses both functions above to loop through the dataset


WarpDist <- function(Data, a = NewRow, b = NewCol){
    for(i in 1:4) {
       Je[i] = minFUN(Data, a, b)
   # Next Start Point
       NSP = NextRC(Data, a,b)
       NewRow = as.numeric(NSP[1,1])
   NewCol = as.numeric(NSP[1,2])    
       a = NewRow
   b = NewCol
}
return(Je)
}

Value=WarpDist(Data = Data, a = NewRow, b = NewCol)

warpo = Data[1,1] + sum(Value)

w = sqrt(warpo)

结果是从第一行到最后一行的最小路径

 Value
[1] 4 1 2 4 6

结果省略了9和3,因为它已经在最后一行了。

时间:

Time difference of 0.08833408 secs