[R] Diagonal matrix with off diagonal elements

Gabor Grothendieck ggrothendieck at gmail.com
Fri Dec 21 23:42:55 CET 2007


On Dec 21, 2007 3:58 PM, Jonas Malmros <jonas.malmros at gmail.com> wrote:
> I wonder if there is a function in R with which I can create a square
> matrix with elements off main diagonal (for example one diagonal below
> the main diagonal).

Try this and adjust the formula for other patterns:

> mm <- matrix(nr = 5, nc = 5)
> (row(mm) == col(mm) + 1) + 0
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    1    0    0    0    0
[3,]    0    1    0    0    0
[4,]    0    0    1    0    0
[5,]    0    0    0    1    0



More information about the R-help mailing list