PythonDaniel
PythonDaniel

Reputation: 31

Replace a specific row depending on input in a matrix with zeros

I want to create a function which replaces the a chosen row of a matrix with zeros. I try to think of the matrix as arbitrary but for this example I have done it with a sample 3x3 matrix with the numbers 1-9, called a_matrix

1   4   7
2   5   8
3   6   9

I have done:

zero_row <- function(M, n){
   n <- c(0,0,0)
   M*n
}

And then I have set the matrix and tried to get my desired result by using my zero_row function

mat1 <- a_matrix
zero_row(M = mat1, n = 1)
zero_row(M = mat1, n = 2)
zero_row(M = mat1, n = 3)

However, right now all I get is a matrix with only zeros, which I do understand why. But if I instead change the vector n to one of the following

n <- c(0,1,1)
n <- c(1,0,1)
n <- c(1,1,0)

I get my desired result for when n=1, n=2, n=3 separately. But what i want is, depending on which n I put in, I get that row to zero, so I have a function that does it for every different n, instead of me having to change the vector for every separate n. So that I get (n=2 for example)

1   4   7
0   0   0
3   6   9

And is it better to do it in another form, instead of using vectors?

Upvotes: 0

Views: 109

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76470

Here is a way.

zero_row <- function(M, n){
  stopifnot(n <= nrow(M))
  M[n, ] <- 0
  M
}

A <- matrix(1:9, nrow = 3)
zero_row(A, 1)
zero_row(A, 2)
zero_row(A, 3)

Upvotes: 1

Related Questions