1

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)

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

hey, you should add an option byrow=TRUE to that matrix() or it won't work as advertised:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.