Goutham
Goutham

Reputation: 2859

R : Updating a matrix given a set of indices

I have a matrix(initialized to zeros) and a set of indices. If the i'th value in indices is j, then I want to set the (j,i)th entry of the matrix to 1.

For eg:

> m = matrix(0, 10, 7)

> indices
[1]  2  9  3  4  5  1 10

And the result should be

> result
      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
 [1,]    0    0    0    0    0    1    0
 [2,]    1    0    0    0    0    0    0
 [3,]    0    0    1    0    0    0    0
 [4,]    0    0    0    1    0    0    0
 [5,]    0    0    0    0    1    0    0
 [6,]    0    0    0    0    0    0    0
 [7,]    0    0    0    0    0    0    0
 [8,]    0    0    0    0    0    0    0
 [9,]    0    1    0    0    0    0    0
[10,]    0    0    0    0    0    0    1

I asked a somewhat related question a little while back, which used a vector instead of a matrix. Is there a similar simple solution to this problem?

Upvotes: 0

Views: 63

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193527

For the record, the answer in your linked question can easily be adapted to suit this scenario too by using sapply:

indices <- c(2,  9,  3,  4,  5,  1, 10)
sapply(indices, tabulate, nbins = 10)
#       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#  [1,]    0    0    0    0    0    1    0
#  [2,]    1    0    0    0    0    0    0
#  [3,]    0    0    1    0    0    0    0
#  [4,]    0    0    0    1    0    0    0
#  [5,]    0    0    0    0    1    0    0
#  [6,]    0    0    0    0    0    0    0
#  [7,]    0    0    0    0    0    0    0
#  [8,]    0    0    0    0    0    0    0
#  [9,]    0    1    0    0    0    0    0
# [10,]    0    0    0    0    0    0    1

For small datasets you might not notice the performance difference, but Josh's answer, which uses matrix indexing, would definitely be much faster, even if you changed my answer here to use vapply instead of sapply.

Upvotes: 1

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162321

## OP's example data
m = matrix(0, 10, 7)
j <- c(2,  9,  3,  4,  5,  1, 10)

## Construct a two column matrix of indices (1st column w. rows & 2nd w. columns)
ij <- cbind(j, seq_along(j))
## Use it to subassign into the matrix
m[ij] <- 1
m
#       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#  [1,]    0    0    0    0    0    1    0
#  [2,]    1    0    0    0    0    0    0
#  [3,]    0    0    1    0    0    0    0
#  [4,]    0    0    0    1    0    0    0
#  [5,]    0    0    0    0    1    0    0
#  [6,]    0    0    0    0    0    0    0
#  [7,]    0    0    0    0    0    0    0
#  [8,]    0    0    0    0    0    0    0
#  [9,]    0    1    0    0    0    0    0
# [10,]    0    0    0    0    0    0    1

Upvotes: 1

Related Questions