# [R] place values into a matrix efficiently?

Rolf Turner rolf.turner at xtra.co.nz
Sun Nov 20 05:16:51 CET 2011

```On 20/11/11 16:27, Carl Witthoft wrote:
> This question attacked me as I was thinking about matrix value updates.
>
> I probably will never need to do this, but wanted to ask if there are
> efficient methods to perform the for-loop in the following sequence.
>
> %xymat<-matrix(rep(0,100) nr=10,nc=10)  # empty matrix
> %x<-1:10
> %y<-sample.int(10,10,rep=T)
>
> %for (j in 1:10) xymat[x[j],y[j]] <- some_function(x[j],y[j]) #to
> create either false-color or 3D map .
> plot(0:1,0:1,t='n')
> % rasterImage(xymat/max(xymat),0,0,1,1,interp=F)
>
> This will produce a raster image of the original data(x vs y) that
> looks like plot(x,y) .
>
> Anyway, I just seem to be blanking: is there some vectorized way to
> place values, or even a constant value, into all elements of xymat
> whose row,col coordinates match ordered pairs in x and y ?

Yes.  Use ``xymat[m]'' where m is a 2-column matrix of row and column
indices.

E.g.:

xymat <- matrix(0,nrow=10,ncol=10)
x <- 1:10
y <- sample.int(10,10,rep=TRUE)
set.seed(42)
for (j in 1:10) xymat[x[j],y[j]] <- runif(1)

gorp <- matrix(0,nrow=10,ncol=10)
set.seed(42)
gorp[cbind(x,y)] <- runif(10)
all.equal(xymat,gorp) # TRUE!!!

cheers,

Rolf Turner

```