Home > front end >  How to replace 0s in a matrix with a pre-specified value
How to replace 0s in a matrix with a pre-specified value

Time:12-28

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?

CodePudding user response:

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 :-) enter image description here

CodePudding user response:

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

CodePudding user response:

Use replace

replace(mat, !mat, 0.3)

Or may also do

(!mat) * 0.3   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
  • Related