Shrey_var
Shrey_var

Reputation: 11

Replacing the values of Subsetted Matrix with an another matrix in R

I have an all zero sparse matrix K1 with the dimensions (9x3). I wanted to replace certain values of this matrix with an another matrix. Also, instead of numerical indexing, I have used variable indexing to make it more dynamic. The codes are as follows -

n <- 3 
library(Matrix)
K1 <- Matrix(0, n*n, n*(n-1)/2, sparse = TRUE)
for (i in 1:(n - 1)) {
  K1[2 + (i - 1)*(n + 1):i*n, 
     1 + (i - 1)*(n - i/2):i*(n - i)*(i + 1)/2] <- diag(n - i)
}

However, it shows the error -

Error in replCmat4(x, i1 = if (iMi) 0:(di[1] - 1L) else .ind.prep2(i,  : 
  too many replacement values

Sometimes this error as well -

Error in intI(i, n = di[margin], dn = dn[[margin]], give.dn = FALSE) : 
  index larger than maximal 9

But, when I run the Similar code in MATLAB, it runs perfectly. MATLAB code -

n = 3 
K1 = sparse(n*n,n*(n-1)/2);
for i = 1:n-1
    K1(2+(i-1)*(n+1):i*n,1+(i-1)*(n-i/2):i*n-i*(i+1)/2) = eye(n-i);
end

And the output which MATLAB gives is -

K1 =

   (2,1)             1.00
   (3,2)             1.00
   (6,3)             1.00

Thus, above is my desired output as well.

Can someone tell what is going wrong when I am trying to execute the same in R.

I appreciate the help. Thanks.

Upvotes: 1

Views: 402

Answers (1)

Peace Wang
Peace Wang

Reputation: 2419

Please put the index in a pair of braket, otherwise they may be explained differently in R and Matlab.

K1[(2+(i-1)*(n+1)):(i*n), (1+(i-1)*(n-i/2)):(i*(n-i)*(i+1)/2)]

Upvotes: 1

Related Questions