简体   繁体   中英

Change multiple Matrix elements by Index Vectors

I have a matrix

myMatrix <- matrix(data = 0, nrow = 4, ncol = 4)

     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]    0    0    0    0
[3,]    0    0    0    0
[4,]    0    0    0    0

and I want to change particular values

myMatrix[1,1] <- 1
myMatrix[2,3] <- 1
myMatrix[4,4] <- 1

myMatrix

     [,1] [,2] [,3] [,4]
[1,]    1    0    0    0
[2,]    0    0    1    0
[3,]    0    0    0    0
[4,]    0    0    0    1

How can I do this efficient/elegantly if I have two vectors containing the row and column indexes:

rowIndexes <- c(1,2,4)
colIndexes <- c(1,3,4)

The assigned value is constant (in this case 1 ).

I know how to do it with a for -loop, but this feels inefficient.

We can cbind the row/column index, subset the myMatrix and assign values to 1

myMatrix[cbind(rowIndexes, colIndexes)] <- 1
myMatrix
#     [,1] [,2] [,3] [,4]
#[1,]    1    0    0    0
#[2,]    0    0    1    0
#[3,]    0    0    0    0
#[4,]    0    0    0    1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM