Given two matrices with the same number of columns.
m1 <- matrix(1:12, ncol=3)
m2 <- matrix(10:2, ncol=3)
Say I have a function that takes two vectors and do something like the product of each vectors min (toy example):
fun <- function(v1, v2)(min(v1)*min(v2))
I can't get my head around how to do the function on all combinations of columns by using two nested apply calls. To use apply on m1 versus first column is like:
apply(m1, 2, fun, m2[,1])
Im stuck with looping through all m2's columns like:
m3<-matrix(NA, ncol=3, nrow=3)
for(c in 1:ncol(m2)){
m3[,c] <- apply(m1, 2, fun, m2[,c])
}
This gives
> m3
[,1] [,2] [,3]
[1,] 10 9 8
[2,] 50 45 40
[3,] 90 81 72
So how to frame this loop as an apply ?
EDIT: the code had an error - sorry. See edit