Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 204922

Simultaneously applying each element of a matrix to a function in R

$
0
0

I simulated three matrixes and hope to realize a function.

It is hard to explain this function but I think the folllowing code of FOR LOOP is nice and simple to interpret what I want to do.

A=matrix(1:10000,100,100)
B=matrix(2:10001,100,100)
C=matrix(3:10002,100,100)

for (i in 1:100) {
  for (j in 1:100) {
    print(min(C[B>A[i,j]]))
  }
}

However, in fact the matrix of each would be much much bigger, for example 1000 * 1000, resulting in a huge time consumption by FOR LOOP. I tried apply() in two dimension but it doesn't improve at all according to system.time().

apply(A, 1:2, function(x) print(min(C[B>x])))

I wonder if there is any way to optimize this function to make it faster, or in brief, to use each element of matrix A simultaneously.

Many thanks advanced!


Viewing all articles
Browse latest Browse all 204922

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>