简体   繁体   中英

nested loop matrix index in R

I am learning matrix multiplication in R and following is what I want to achieve. I am doing this purely to upscale my skills in R. Following is the kind of matrix I am working with:

m <- matrix(1, 100, 10)

I have matrix with only element 1 with 100 rows and 10 columns. Now I want to replace for column 1 with 0 from row1 to row10. Then for the second column, I want to replace 1 with zeros from row 11 to row 20. Similarly for for the third column, I want to replace 1 with zeros from row 21 to row 30 and similarly for the rest up too column 10. Following my my example

m <- matrix(1, 100, 10)                
for(j in 1:10){
   for(i in (j-1)*10+1: j*10){
     m[i,j] <-0
   }
}

I was quite confident that my logic was correct but every time I run my code, I get following error message Subscripts out of bounds Call . I tried couple days now and I could not resolve this problem. I would highly appreciate for any hints or direct solutions to fix this. Many thanks in advance.

You could use just one variable, which I think would be easier. For each column, j, get the lower and upper range of row indices and assign as 0.

for(j in 1:10){
    row_lower <- (j-1)*10+1
    row_upper <- j*10
    m[row_lower: row_upper, j] <- 0
}

Returns 0's in your specified range.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM