Adrian
Adrian

Reputation: 9803

How to pad vectors and matrices with 0s

vec_length <- 4
nonzero_ind <- c(1, 3)
zero_ind <- c(2, 4)

Vector:

I currently have a vector called vec that contains 2 elements.

vec <- c(22, -5)

I want to obtain a vector of length vec_length that expands vec by adding 0s. The position of these 0s are specified by zero_ind. That is, I want a vector that looks like:

> expanded_vec
[1] 22  0 -5  0

Matrix

I currently have a 2x2 matrix called mat that corresponds to vec.

> mat
     [,1] [,2]
[1,]    1    2
[2,]    2    3

I want to obtain a vec_length by vec_length matrix where there are 0s in the (i,j)-th position if either i OR j is one of the nonzero_ind. That is, I want a matrix that looks like:

> expected_mat
     [,1] [,2] [,3] [,4]
[1,]    1    0    2    0
[2,]    0    0    0    0
[3,]    2    0    3    0
[4,]    0    0    0    0

Upvotes: 1

Views: 349

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 102241

Maybe you can try kronecker like below

> kronecker(vec,c(1,0))
[1] 22  0 -5  0

> kronecker(mat,matrix(c(1,0,0,0),nrow(mat)))
     [,1] [,2] [,3] [,4]
[1,]    1    0    2    0
[2,]    0    0    0    0
[3,]    2    0    3    0
[4,]    0    0    0    0

Upvotes: 0

GKi
GKi

Reputation: 39707

For the vector:

"[<-"(numeric(vec_length), nonzero_ind, vec)
#[1] 22  0 -5  0

"[<-"(numeric(vec_length), seq_len(vec_length)[-zero_ind], vec)
#[1] 22  0 -5  0

x <- numeric(vec_length)
(x[nonzero_ind] <- vec)
#[1] 22  0 -5  0

x <- numeric(vec_length)
(x[-zero_ind] <- vec)
#[1] 22  0 -5  0

and the Matrix:

i <- "[<-"(rep(NA,vec_length), nonzero_ind, seq_along(nonzero_ind))
mat <- mat[i, i]
mat[is.na(mat)] <- 0
mat
#     [,1] [,2] [,3] [,4]
#[1,]    1    0    2    0
#[2,]    0    0    0    0
#[3,]    2    0    3    0
#[4,]    0    0    0    0

or

mat_out <- matrix(0, vec_length, vec_length)
mat_out[nonzero_ind, nonzero_ind] <- mat
mat_out
#     [,1] [,2] [,3] [,4]
#[1,]    1    0    2    0
#[2,]    0    0    0    0
#[3,]    2    0    3    0
#[4,]    0    0    0    0

Upvotes: 2

s_baldur
s_baldur

Reputation: 33508

One example:

# Input data
vec_inp <- c(22, -5)
mat_inp <- matrix(c(1, 2, 2, 3), ncol = 2)


# Vector case
update_vec <- function(inp, len, nzi) {
  replace(x = vector(mode = 'double', length = len), list = nzi, values = inp)
}
update_vec(vec_inp, vec_length, nonzero_ind)
# [1] 22  0 -5  0

# Matrix case, work column by column
mat_out <- matrix(vector(mode = 'double', length = vec_length^2), ncol = vec_length)
for (i in seq_along(nonzero_ind)) {
  mat_out[, nonzero_ind[i]] <- update_vec(mat_inp[, i], vec_length, nonzero_ind)
}
mat_out
#      [,1] [,2] [,3] [,4]
# [1,]    1    0    2    0
# [2,]    0    0    0    0
# [3,]    2    0    3    0
# [4,]    0    0    0    0

Upvotes: 0

Related Questions