Snoop Dogg
Snoop Dogg

Reputation: 391

Replacing values in the columns of a matrix according to a vector of indices?

I have a matrix of zeroes:

M <- matrix(0, nrow = 10, ncol = 5)

and a vector of indices

V <- c(1,5,3,2,3,4,1,3,2,4)

I want to replace the entries M[i,V[i]] by 1, i in 1:10. How can I do this without using brute force (for loop)? Below is the code to do so using brute force, which is not efficient in higher dimensions:

for(i in 1:10) M[i,V[i]] = 1

Upvotes: 2

Views: 32

Answers (1)

Sotos
Sotos

Reputation: 51622

You can make a matrix from your vector V and use it directly, i.e.

M[matrix(c(seq_along(V), V), ncol = 2)] <- 1

Upvotes: 3

Related Questions