1

我在下面有这个矩阵

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

不知道为什么会这样……

4

2 回答 2

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)

我希望这会有所帮助。

于 2018-11-05T16:52:05.863 回答
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
于 2018-11-06T18:35:36.237 回答