Rojer
Rojer

Reputation: 335

The best way for making speciall matrix

I want to make the below matrix in r:

1 0 0 4
0 2 0 5
0 0 3 6

I used the below code:

matrix(c(1,0,0,0,2,0,0,0,3,4,5,6),nrow=3)

My code works. But I do not like my solution way. I am thinking to find the simplest way for making this matrix. Do you think my code is the simplest code for making this matrix? If not, could anyone writes a simpler code than my one?

Upvotes: 3

Views: 53

Answers (1)

Martin Gal
Martin Gal

Reputation: 16988

Your first matrix

> cbind(diag(1:3), 4:6)
     [,1] [,2] [,3] [,4]
[1,]    1    0    0    4
[2,]    0    2    0    5
[3,]    0    0    3    6

Your second one

> matrix(1, nrow=3, ncol=3) - diag(1, 3)
     [,1] [,2] [,3]
[1,]    0    1    1
[2,]    1    0    1
[3,]    1    1    0

Your third

> matrix(seq(1, 35, 2), nrow=3, byrow=TRUE)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    3    5    7    9   11
[2,]   13   15   17   19   21   23
[3,]   25   27   29   31   33   35

and your final

> matrix(0.5, nrow=3, ncol=3) + diag(0.5, 3)
     [,1] [,2] [,3]
[1,]  1.0  0.5  0.5
[2,]  0.5  1.0  0.5
[3,]  0.5  0.5  1.0

As @jay.sf pointed out, there is a more sophisticated solution for the second and fourth matrix:

# second matrix
`diag<-`(matrix(1, 3, 3), 0)
# fourth matrix
`diag<-`(matrix(0.5, 3, 3), 1)

Upvotes: 2

Related Questions