Skip to content

Help on a matrix task

3 messages · Serguei Kaniovski, JeeBee, Adrian Dusa

#
Hello,

Being new to R, I am completely stuck with the following problem. Please
help to find a general solution to the following matrix task:
Given:

N<-4

input_mat<-matrix(c(1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
			1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0,
			1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0,
			1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0),ncol=N)

combin_mat<-matrix(c(1, 2,
			1, 3,
			1, 4,
			2, 3,
			2, 4,
			3, 4),ncol=choose(N,2))

Find the indices of rows in "input_mat", whose elements indicated by the
pair of elements in each column of "combin_mat", are equal 1. So, for
the first
column of combin_mat (1,2) the answer should be 1,2,3, and 4th row of
"input_mat" has 1 as the first and second element, for the secondcolumn
of combin_mat (1,3) the answer should be 1,2,5,6, for the third column
of combin_mat (1,4) the answer should be 1,3,5,7, an so on.

"input_mat" is the matrix of binary representations of the first 2^N-1
decimals in the descending order, here N=4, so 7,6,...,0. "combin_mat"
is the matrix of all combinations of N by 2.
#
Here is one possible solution:

for(cr in seq(1, dim(combin_mat)[2])) {
  W = which(input_mat[,combin_mat[1,cr]] == 1 & 
            input_mat[,combin_mat[2,cr]] == 1)
  cat("Combination", cr, "(", combin_mat[,cr], ") :", W, "\n")
}

JeeBee.

---
Full program:

N = 4

input_numbers = seq((2^N)-1, 0, -1)
# convert to binary matrix
input_mat = NULL
for(i in seq(N-1,0,-1)) {
  new_col = input_numbers %% 2
  input_mat = cbind(new_col, input_mat)
  input_numbers = (input_numbers - new_col) / 2
}
colnames(input_mat) = NULL

library(gtools)
combin_mat = t(combinations(n=N, r=2, v=1:N, set=TRUE, repeats.allowed=FALSE))

for(cr in seq(1, dim(combin_mat)[2])) {
  W = which(input_mat[,combin_mat[1,cr]] == 1 & 
            input_mat[,combin_mat[2,cr]] == 1)
  cat("Combination", cr, "(", combin_mat[,cr], ") :", W, "\n")
}
2 days later
#
On Tuesday 06 December 2005 14:41, JeeBee wrote:
A little late, but wouldn't be more simple to create input_mat with:
N <- 4
input_mat <- matrix(NA, ncol=N, nrow=2^N)
for (i in 1:N) input_mat[,i] <- c(rep(0, 2^(N - i)), rep(1, 2^(N - i)))

HTH,
Adrian