# Re: [R] Diagonal matrix with off diagonal elements

From: Martin Maechler <maechler_at_stat.math.ethz.ch>
Date: Mon, 24 Dec 2007 14:00:22 +0100

>>>>> "PD" == Peter Dalgaard <p.dalgaard_at_biostat.ku.dk> >>>>> on Sat, 22 Dec 2007 11:29:30 +0100 writes:

PD> Chris Stubben wrote:
>> Also try the odiag function in the demogR package
>>
>> odiag( 1:5, -1)
>> [,1] [,2] [,3] [,4] [,5] [,6]
>> [1,] 0 0 0 0 0 0
>> [2,] 1 0 0 0 0 0
>> [3,] 0 2 0 0 0 0
>> [4,] 0 0 3 0 0 0
>> [5,] 0 0 0 4 0 0
>> [6,] 0 0 0 0 5 0
>>
>> Chris
>>
>>
PD> Also, this sort of pattern works

>> m <- matrix(0,6,6)
>> diag(m[-1,])<-1:5
>> m

```    PD> [,1] [,2] [,3] [,4] [,5] [,6]
PD> [1,]    0    0    0    0    0    0
PD> [2,]    1    0    0    0    0    0
PD> [3,]    0    2    0    0    0    0
PD> [4,]    0    0    3    0    0    0
PD> [5,]    0    0    0    4    0    0
PD> [6,]    0    0    0    0    5    0

```

Yes, indeed, *the* S- / R- answer.

and note that this also works with sparse matrices:

```> library(Matrix)
> m <- Matrix(0,6,6)
> diag(m[-1,]) <- 1:5
> m
6 x 6 sparse Matrix of class "dgCMatrix"

[1,] . . . . . .
[2,] 1 . . . . .
[3,] . 2 . . . .
[4,] . . 3 . . .
```

[5,] . . . 4 . .
[6,] . . . . 5 .
• - - - - - - - - - -

Merry Christmas' Eve to all R-helpers!

Martin Maechler

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Mon 24 Dec 2007 - 13:10:17 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 24 Dec 2007 - 14:30:22 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.