[R] filling a matrix who's entries are a function of the ind
(Ted Harding)
Ted.Harding at nessie.mcc.ac.uk
Sat Aug 23 23:25:07 CEST 2003
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 ------------------------------
More information about the R-help
mailing list