Reputation: 5789
How can i turn M unto a 12 by m matrix of numbers (e.g. with one bit per cell):
library(R.utils)
m<-5
k<-12
W<-sample(1:(2**m),k)
M<-matrix(intToBin(V),k,1)
Upvotes: 1
Views: 785
Reputation: 145895
intToBin
is returning characters, so use strsplit
to break it into individual digits (bits) before putting in a matrix.
m <- 5
k <- 12
W <- sample(1:(2**m), k)
M <- matrix(as.numeric(unlist(strsplit(intToBin(W), ""))), nrow= k, byrow = TRUE)
> M
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 0 0 0 0 0
[2,] 0 1 1 0 0 0
[3,] 0 0 0 1 1 0
[4,] 0 1 0 0 1 1
[5,] 0 1 0 1 1 0
[6,] 0 1 1 1 0 0
[7,] 0 0 0 0 0 0
[8,] 0 1 1 1 1 0
[9,] 1 1 0 1 0 1
[10,] 1 0 0 1 1 1
[11,] 0 0 1 1 1 1
[12,] 0 0 1 1 0 1
Upvotes: 1
Reputation: 115390
intToBin
will return a character string of the binary representation.
You can split this string, convert to integer, then combine the rows.
M<-do.call(rbind, lapply(strsplit(intToBin(W),''), as.integer))
Upvotes: 2