Question

I have two matrices A and B. Matrix B is a two-column matrix, each row containing one index of an element in matrix A. I want to change those elements in matrix A, which are indexed by each row in matrix B, to 0.

Is there a way to avoid using the loop shown below?

> A <- matrix(1:12, 3, 4)
> B <- matrix(c(1, 2, 2, 2, 3, 4), byrow = TRUE, ncol = 2)
> A
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> B
     [,1] [,2]
[1,]    1    2
[2,]    2    2
[3,]    3    4
> for (i in 1:nrow(B)) {
+     A[B[i, 1], B[i, 2]] <- 0
+ }
> A
     [,1] [,2] [,3] [,4]
[1,]    1    0    7   10
[2,]    2    0    8   11
[3,]    3    6    9    0
Was it helpful?

Solution

It's done like this

A[B] <- 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top