# [R] create diagonal matrix within a for cycle

Robin Hankin r.hankin at noc.soton.ac.uk
Tue Oct 23 16:39:52 CEST 2007

```Hello

I suspect that adiag() of the magic package is what you need:

> library(magic)

Attaching package: 'magic'

The following object(s) are masked from package:mgcv :

magic

> a <- matrix(1:4,2,2)
> b <- matrix(1:9,3,3)
[,1] [,2] [,3] [,4] [,5]
[1,]    1    3    0    0    0
[2,]    2    4    0    0    0
[3,]    0    0    1    4    7
[4,]    0    0    2    5    8
[5,]    0    0    3    6    9
>

HTH

rksh

On 23 Oct 2007, at 14:14, Niccolò Bassani wrote:

> Dear R users, I'm trying to build a diagonal matrix from a group of
> matrices. These matrices have been built in a for loop. That is, I've
> subsetted a preliminar matrix to obtain a certain number of square
> sub-matrices, and now I need to create a diagonal out of these.
> Suppose my matrix is a square matrix 21x21, and that I want to
> diagonalize
> 616 submatrices of this one. To do this I do:
>
> diag <- rep(1,21)
> work.cov <- matrix(0,21,21)
> diag(work.cov) <- diag
> samp <- sample(seq(1:21),616,replace=T)
> for (i in 1:length(samp)){
> A <- work.cov[1:samp[i],1:samp[i]]
> }
>
> Now, I want to put these 616 square matrices on the diagonal of a new
> matrix. The question is: how I can I do this? I know there's a
> function
> bdiag that creates diagonal matrix with various elements (vectors and
> matrices), but the problem here's that my matrices exists only in
> the loop,
> not outside of it, and they all correspond to the same matrix V
> computed
> under different values of i.
> niccolò
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> guide.html
> and provide commented, minimal, self-contained, reproducible code.

--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
tel  023-8059-7743

```