Douglas G. Scofield
2003-Aug-23 20:39 UTC
[R] filling a matrix who's entries are a function of the indices?
Dear R list, What's the best way in R to fill a matrix who's entries depend on some function of the indices? I'm currently doing: Q <- matrix(0, k, k) for (A in 1:k) { for (B in 1:k) { Q[A,B] <- my.function(A,B) } } but I wonder if there is a more terse way. Regards, Douglas Scofield Department of Biology d.scofield at umiami.edu University of Miami off: (305) 284-3778 P.O. Box 249118 fax: (305) 284-3039 Coral Gables, FL 33124-0421
(Ted Harding)
2003-Aug-23 21:25 UTC
[R] filling a matrix who's entries are a function of the ind
On 23-Aug-03 Douglas G. Scofield wrote:> What's the best way in R to fill a matrix who's entries depend on some > function of the indices? I'm currently doing: > > Q <- matrix(0, k, k) > for (A in 1:k) { > for (B in 1:k) { > Q[A,B] <- my.function(A,B) > } > } > > but I wonder if there is a more terse way.Something on the following lines?> xx<-matrix(rep(c(1,2,3),3),ncol=3) > xx[,1] [,2] [,3] [1,] 1 1 1 [2,] 2 2 2 [3,] 3 3 3> yy<-t(xx) > yy[,1] [,2] [,3] [1,] 1 2 3 [2,] 1 2 3 [3,] 1 2 3> myfun<-function(XX,YY){(XX-YY)^2} > myfun(xx,yy)[,1] [,2] [,3] [1,] 0 1 4 [2,] 1 0 1 [3,] 4 1 0 [The above is inspired by the matlab/octave function "meshdom"] Best wishes, Ted. -------------------------------------------------------------------- E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk> Fax-to-email: +44 (0)870 167 1972 Date: 23-Aug-03 Time: 22:25:07 ------------------------------ XFMail ------------------------------