[R] Diagonal matrix with off diagonal elements

Domenico Vistocco vistocco at unicas.it
Fri Dec 21 22:24:29 CET 2007


Jonas Malmros wrote:
> Hi, everyone
>
> 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).
>
> Thanks in advance!
>
>   

You could combine rbind, diag and cbind:
rbind(rep(0,3),cbind(diag(2),rep(0,2)))
rbind(rep(0,4),cbind(diag(3),rep(0,3)))
.......

A simple function:

belowDiagonal = function(x)
{
    diagBelow=rbind(rep(0,length(x)+1),cbind(diag(x),rep(0,length(x))))
    return(diagBelow)
}


belowDiagonal(7)
belowDiagonal(1:5)

domenico



More information about the R-help mailing list