Anil Sarode
Anil Sarode

Reputation: 301

How to form the matrix of logical '1' and '0' using two vectors and logical operators in r?

Here is Matlab code to form the matrix of logical values of '0' and '1'

 A=[1 2 3 4 5 6 7 8 9 10  ];
 N = numel(A);
 step = 2;    % Set this to however many zeros you want to add each column
 index = N:-step:1;
 val = (1:N+step).' <= index;

Which result in

 val=

 1     1     1     1     1
 1     1     1     1     1
 1     1     1     1     0
 1     1     1     1     0
 1     1     1     0     0
 1     1     1     0     0
 1     1     0     0     0
 1     1     0     0     0
 1     0     0     0     0
 1     0     0     0     0
 0     0     0     0     0
 0     0     0     0     0

How to do same task in r ,particularly val = (1:N+step).' <= indexthis step?

Upvotes: 1

Views: 149

Answers (1)

akrun
akrun

Reputation: 887511

One option is

i <- seq_len(ncol(m1))
sapply(rev(i), function(.i) {
         m1[,.i][sequence(.i *2)] <- 1
         m1[,.i]
   })
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    1    1    1    1
# [2,]    1    1    1    1    1
# [3,]    1    1    1    1    0
# [4,]    1    1    1    1    0
# [5,]    1    1    1    0    0
# [6,]    1    1    1    0    0
# [7,]    1    1    0    0    0
# [8,]    1    1    0    0    0
# [9,]    1    0    0    0    0
#[10,]    1    0    0    0    0
#[11,]    0    0    0    0    0
#[12,]    0    0    0    0    0

Or vectorize it

i1 <- rep(i,  rev(2*i))
m1[cbind(ave(i1, i1, FUN = seq_along), i1)] <- 1
m1
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    1    1    1    1
# [2,]    1    1    1    1    1
# [3,]    1    1    1    1    0
# [4,]    1    1    1    1    0
# [5,]    1    1    1    0    0
# [6,]    1    1    1    0    0
# [7,]    1    1    0    0    0
# [8,]    1    1    0    0    0
# [9,]    1    0    0    0    0
#[10,]    1    0    0    0    0
#[11,]    0    0    0    0    0
#[12,]    0    0    0    0    0

Or another option without creating a matrix beforehand

n <- 5
i1 <- seq(10, 2, by = -2)
r1 <- c(rbind(i1, rev(i1)))
matrix(rep(rep(c(1, 0), n), r1), ncol = n)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    1    1    1    1
# [2,]    1    1    1    1    1
# [3,]    1    1    1    1    0
# [4,]    1    1    1    1    0
# [5,]    1    1    1    0    0
# [6,]    1    1    1    0    0
# [7,]    1    1    0    0    0
# [8,]    1    1    0    0    0
# [9,]    1    0    0    0    0
#[10,]    1    0    0    0    0
#[11,]    0    0    0    0    0
#[12,]    0    0    0    0    0

data

m1 <- matrix(0, 12, 5)

Upvotes: 2

Related Questions