AggieIE
AggieIE

Reputation: 125

Working With a Diagonal Matrix

Hi I'm pretty much stumped on on trying to figure this out and could use a little help. Basically, I have a n x n matrix where the diagonal is set to a value k and every other value is 0.

  1 2 3 4 5
1 k 0 0 0 0 
2 0 k 0 0 0
3 0 0 k 0 0
4 0 0 0 k 0
5 0 0 0 0 k

Basically, I need to be able to make two other diagonals in this matrix with the value of 1 so it ends up looking like this:

  1 2 3 4 5
1 k 1 0 0 0
2 1 k 1 0 0
3 0 1 k 1 0
4 0 0 1 k 1
5 0 0 0 1 k

So far all I have for code is being able to make the diagonal matrix m=diag(k,n,n) but I have no idea on how to add the two other diagonals. Would I use apply() and cbind() or rbind()?

Upvotes: 2

Views: 133

Answers (2)

Frash
Frash

Reputation: 728

Try this function, it will make a matrix of dimensions row X col and diagonal of the numeric n.

matfun <- function(diag=n, row=4,col=4){
  x = diag(1,row,col)
  diag*x+rbind(as.vector(rep(0,col)),x[1:(row-1),])+cbind(as.vector(rep(0,row)),x[,1:(col-1)])
}

HTH

Upvotes: 0

user20650
user20650

Reputation: 25914

You can use col and row to create and index to subset and assign the upper and lower diagonals.

k=3
m <- k* diag(6)
m[abs(row(m) - col(m)) == 1] <- 1
m
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    3    1    0    0    0    0
#[2,]    1    3    1    0    0    0
#[3,]    0    1    3    1    0    0
#[4,]    0    0    1    3    1    0
#[5,]    0    0    0    1    3    1
#[6,]    0    0    0    0    1    3

If you wanted reverse diagonals you could use col(m) - row(m)

Upvotes: 2

Related Questions