Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

Finding index of array of matrices, that is closest to each element of another matrix in R

I have an array Q which has size nquantiles by nfeatures by nfeatures. In this, essentially the slice Q[1,,] would give me the first quantile of my data, across all nfeatures by nfeatures of my data.

What I am interested in, is using another matrix M (again of size nfeatures by nfeatures) which represents some other data, and asking the question to which quantile do each of the elements in M lie in Q.

What would be the quickest way to do this?

I reckon I could do double for loop across all rows and columns of the matrix M and come up with a solution similar to this: Finding the closest index to a value in R

But doing this over all nfeatures x nfeatures values will be very inefficient. I am hoping that there might exist a vectorized way of approaching this problem, but I am at a lost as to how to approach this.

Here is a reproducible way of the slow way I can approach the problem with O(N^2) complexity.

#Generate some data
set.seed(235)
data             = rnorm(n = 100, mean = 0, sd = 1)
list_of_matrices = list(matrix(data = data[1:25], ncol = 5, nrow = 5),
                        matrix(data = data[26:50], ncol = 5, nrow = 5),
                        matrix(data = data[51:75], ncol = 5, nrow = 5),
                        matrix(data = data[76:100], ncol = 5, nrow = 5))
#Get the quantiles  (5 quantiles here)
Q <- apply(simplify2array(list_of_matrices), 1:2, quantile, prob = c(seq(0,1,length = 5)))
#dim(Q)
#Q should have dims nquantiles by nfeatures by nfeatures

#Generate some other matrix M (true-data)
M             = matrix(data = rnorm(n = 25, mean = 0, sd = 1), nrow = 5, ncol = 5)

#Loop through rows and columns in M to find which index of the array matches up closest with element M[i,j]
results = matrix(data = NA, nrow = 5, ncol = 5)
for (i in 1:nrow(M)) {
  for (j in 1:ncol(M)) {
    true_value = M[i,j]
    #Subset Q to the ith and jth element (vector of nqauntiles)
    quantiles  = Q[,i,j]
    results[i,j]    = (which.min(abs(quantiles-true_value)))
  }
}
'''
question from:https://stackoverflow.com/questions/65870510/finding-index-of-array-of-matrices-that-is-closest-to-each-element-of-another-m

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...