Home > OS >  Modifying an matrix surrounding elements of an element?
Modifying an matrix surrounding elements of an element?

Time:10-12

The Question with example: In short I've been trying to learn how to work with matrices in R programming. I've been trying to gain access and modify elements directly surrounding a 1 with some probability of either a 0 or 1. An example would be in the bottom right hand corner of the matrix. Also I've been stumped on the edge cases.

//initial
1 0 0 1 0
1 0 0 0 0
0 0 0 0 0
0 0 0 1 0
0 0 0 0 0
//after
1 1 0 1 0
1 0 0 1 0
0 0 1 0 0
0 0 1 1 0
0 0 0 0 1

What have I tried?

I have tried the for loop approach which hasn't worked at all and also can't handle the edge of the matrix because the index would be out of bound.

  for(row in 1:nrow(y)){
    for(col in 1:ncol(y)){
      if(y[row,col] == 2){
        y[row 1,col] = sample(c(0,1), replace = TRUE, size = 1)
        y[row 1,col 1] = sample(c(0,1), replace = TRUE, size = 1)
        y[row 1,col-1] = sample(c(0,1), replace = TRUE, size = 1)
        y[row-1,col] = sample(c(0,1), replace = TRUE, size = 1)
        y[row-1,col-1] = sample(c(0,1), replace = TRUE, size = 1)
        y[row-1,col 1] = sample(c(0,1), replace = TRUE, size = 1)
        y[row,col 1] = sample(c(0,1), replace = TRUE, size = 1)
        y[row,col-1] = sample(c(0,1), replace = TRUE, size = 1)
      }
    }

CodePudding user response:

You are checking if the value is 2 and not 1 like it is in your example the y[row,col] == 2. This needs to be changed to y[row,col] == 1 if you want the example in the question to work correctly.

You can also add if statements to check if the position you want to change is out of bounds.

y <- mat
for(row in 1:nrow(y)){
  for(col in 1:ncol(y)){
    if(y[row,col] == 1){
      if(row > 1){
        if(col > 1){
          y[row-1,col] <- sample(c(0,1), replace = TRUE, size = 1)
          y[row,col-1] <- sample(c(0,1), replace = TRUE, size = 1)
          y[row-1,col-1] <- sample(c(0,1), replace = TRUE, size = 1)
        }
        if(col < ncol(y)){
          y[row-1,col 1] <- sample(c(0,1), replace = TRUE, size = 1)
          y[row,col 1] <- sample(c(0,1), replace = TRUE, size = 1)
        }
      }
      if(row < nrow(y)){
        if(col > 1){
          y[row 1,col] <- sample(c(0,1), replace = TRUE, size = 1)
          y[row 1,col-1] <- sample(c(0,1), replace = TRUE, size = 1)
        }
        if(col < ncol(y)){
          y[row 1,col 1] <- sample(c(0,1), replace = TRUE, size = 1)
        }
      }
    }
  }
}
  • Related