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! -- Jonas Malmros Stockholm University Stockholm, Sweden
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
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
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
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!
>
> --
> Jonas Malmros
> Stockholm University
> Stockholm, Sweden
>
> ______________________________________________
> 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.
>
>
--
View this message in context:
http://www.nabble.com/Diagonal-matrix-with-off-diagonal-elements-tp14462310p14463831.html
Sent from the R help mailing list archive at Nabble.com.