简体   繁体   中英

How to find the min/max for matrix columns with specifided indexes?

I reading the paper and try to implement the algorithm 2:

在此处输入图像描述

where ave(x,y)=2xy/(x+y).

I have found D1 , D2 :

> dput(D1)
structure(c(0, 0, 0.316227766016838, 0.316227766016838, 0.316227766016838, 
0, 0, 0.316227766016838, 0.316227766016838, 0.316227766016838, 
0.316227766016838, 0.316227766016838, 0, 0.316227766016838, 0.447213595499958, 
0.316227766016838, 0.316227766016838, 0.316227766016838, 0, 0.316227766016838, 
0.316227766016838, 0.316227766016838, 0.447213595499958, 0.316227766016838, 
0), .Dim = c(5L, 5L), .Dimnames = list(c("1", "4", "5", "7", 
"9"), c("1", "4", "5", "7", "9")))
> dput(D2)
structure(c(0, 0.447213595499958, 0.316227766016838, 0, 0.447213595499958, 
0.447213595499958, 0, 0.316227766016838, 0.447213595499958, 0, 
0.316227766016838, 0.316227766016838, 0, 0.316227766016838, 0.316227766016838, 
0, 0.447213595499958, 0.316227766016838, 0, 0.447213595499958, 
0.447213595499958, 0, 0.316227766016838, 0.447213595499958, 0
), .Dim = c(5L, 5L), .Dimnames = list(c("1", "5", "7", "8", "10"
), c("1", "5", "7", "8", "10")))

Then I defined the i, j and r indexes:

> dput(i)
c("4", "9")
> dput(j)
c("8", "10")
> dput(r)
c("1", "5", "7")

and finally

k = length(I)
D = matrix(0, k, k)
x = min(    D1[i, r] + D2[j, r])
y = max(abs(D1[i, r] - D2[j, r]))
D = 2*x*y/(x+y)

The exected answer is symmetric 2x2 matrix, but I have

> D
[1] 0

Also, I have tried to use the apply function:

x = apply(     D1+D2,   1, function(x) min(x)) 
y = apply(abs( D1-D2 ), 1, function(x) max(x))
D = 2*x*y/(x+y)

The answer is the vector:

> D
1 4 5 7 9 
0 0 0 0 0 

Question. How to find the min(), max() for columns with specified indexes?

Try the for loops like below

D <- `dimnames<-`(matrix(NA, length(i),length(j)),list(i,j))
for (ki in i) {
  for (kj in j) {
    x <- min(D1[ki,r] + D2[kj,r])
    y <- max(abs(D1[ki,r] - D2[kj,r]))
    D[ki,kj] <- 2*x*y/(x+y)
  }
}

and you will get

> D
          8        10
4 0.0000000 0.3704839
9 0.3162278 0.4472136

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM