mat <- diag(3)
> mat
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
I have a matrix with 1 along the diagonal and 0 everywhere else. I want to replace the 0s with 0.3, so the matrix looks like
> mat
[,1] [,2] [,3]
[1,] 1 0.3 0.3
[2,] 0.3 1 0.3
[3,] 0.3 0.3 1
What's a quick way of doing this?
Try this sum
mat + 0.3 * (1 - mat)
## [,1] [,2] [,3]
## [1,] 1.0 0.3 0.3
## [2,] 0.3 1.0 0.3
## [3,] 0.3 0.3 1.0
A variation of that is to write it as the following convex combination of mat and 1.
0.7 * mat + 0.3
## [,1] [,2] [,3]
## [1,] 1.0 0.3 0.3
## [2,] 0.3 1.0 0.3
## [3,] 0.3 0.3 1.0
We could create a boolean vector that indicates the 0
and assign it each element which is TRUE
mat[mat == 0] <- 0.3
[,1] [,2] [,3]
[1,] 1.0 0.3 0.3
[2,] 0.3 1.0 0.3
[3,] 0.3 0.3 1.0
G.Grothendieck2 is in front in terms of speed :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With