# [R] filling a matrix who's entries are a function of the ind

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Sun Aug 24 01:19:22 CEST 2003

```(Ted Harding) <Ted.Harding at nessie.mcc.ac.uk> writes:

> 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"]

Also:

> outer(1:3,1:3,myfun)
[,1] [,2] [,3]
[1,]    0    1    4
[2,]    1    0    1
[3,]    4    1    0

which does the same sort of stuff internally. Notice that in either
case, myfun must be vectorized. Otherwise you'll need

> myfun2 <- function(x,y)mapply(myfun,x,y)
> outer(1:3,1:3,myfun2)
[,1] [,2] [,3]
[1,]    0    1    4
[2,]    1    0    1
[3,]    4    1    0

As a slightly silly example try it with

myfun<-function(XX,YY)sum(c(XX,YY)^2)

--
O__  ---- Peter Dalgaard             Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics     2200 Cph. N
(*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907

```