[R] how ot replace the diagonal of a matrix

Marc Schwartz (via MN) mschwartz at mn.rr.com
Tue Oct 3 23:12:52 CEST 2006


On Tue, 2006-10-03 at 17:03 -0400, Duncan Murdoch wrote:
> On 10/3/2006 4:59 PM, roger bos wrote:
> > Dear useRs,
> > 
> > Trying to replace the diagonal of a matrix is not working for me.  I
> > want a matrix with .6 on the diag and .4 elsewhere.  The following
> > code looks like it should work--when I lookk at mps and idx they look
> > how I want them too--but it only replaces the first element, not each
> > element on the diagonal.
> > 
> > mps <- matrix(rep(.4, 3*3), nrow=n, byrow=TRUE)
> > idx <- diag(3)
> > mps
> > idx
> > mps[idx] <- rep(.6,3)
> > 
> > I also tried something along the lines of diag(mps=.6, ...) but it
> > didn't know what mps was.
> 
> Matrix indexing can use a two column matrix, giving row and column 
> numbers.  So you could get what you want by
> 
> mps[cbind(1:n,1:n)] <- 0.6

What's wrong with:

> mps <- matrix(rep(.4, 3*3), nrow = 3, byrow=TRUE)
> mps
     [,1] [,2] [,3]
[1,]  0.4  0.4  0.4
[2,]  0.4  0.4  0.4
[3,]  0.4  0.4  0.4

> diag(mps) <- 0.6

> mps
     [,1] [,2] [,3]
[1,]  0.6  0.4  0.4
[2,]  0.4  0.6  0.4
[3,]  0.4  0.4  0.6

HTH,

Marc Schwartz



More information about the R-help mailing list