[R] Building a Matrix

Liaw, Andy andy_liaw at merck.com
Fri Feb 4 20:05:29 CET 2005


Is this what you want?

> mat <- matrix(0, 4, 4)
> mat[col(mat) > 2 & row(mat) > 2] <- 100
> mat
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]    0    0    0    0
[3,]    0    0  100  100
[4,]    0    0  100  100

Andy

> From: Doran, Harold
> 
> Dear List:
> 
> I am having some difficulty constructing a matrix that must take a
> specific form. The matrix must be have a lower block of 
> non-zero values
> and the rest must all be zero. For example, if I am building an n X n
> matrix, then the first n/2 rows need to be zero and the first n/2
> columns must remain as zero with all other elements having a non-zero
> value that I specify.
> 
> For example, assume I start with the following 4 x 4 matrix:
> 
> vl.mat <- matrix(0,4,4)
> 
>      [,1] [,2] [,3] [,4]
> [1,]    0    0    0    0
> [2,]    0    0    0    0
> [3,]    0    0    0    0
> [4,]    0    0    0    0
> 
> I need for the for the first two columns (4/2) to remain as 
> zero and the
> first two rows (4/2) to remain as zeros. But I need for the 
> bottom block
> to include some values that I specify.
> 
>      [,1] [,2] [,3] [,4]
> [1,]    0    0    0    0
> [2,]    0    0    0    0
> [3,]    0    0  100  100
> [4,]    0    0  100  100
> 
> I know that if I use the following I can build a matrix with values
> along the diagonals where I need them, but I need for the 
> lower block of
> off-diagonals to also be the same value.
> 
> vl.mat <- matrix(0,4,4)
> vl.mat[(col(vl.mat)%%4 == row(vl.mat)%%4)&col(vl.mat)%%4 !=1
> &col(vl.mat)%%4 !=2  ] <- 100
> 
> Can anyone offer a suggestion? Thank you.
> 
> -Harold
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list