简体   繁体   English

R 中的嵌套循环矩阵索引

[英]nested loop matrix index in R

I am learning matrix multiplication in R and following is what I want to achieve.我正在 R 中学习矩阵乘法,以下是我想要实现的。 I am doing this purely to upscale my skills in R.我这样做纯粹是为了提升我在 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.我有一个只有元素1的矩阵,它有 100 行和 10 列。 Now I want to replace for column 1 with 0 from row1 to row10.现在我想用 0 从第 1 行到第 10 行替换第 1 列。 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然后对于第二列,我想将 1 替换为从第 11 行到第 20 行的零。类似地,对于第三列,我想将 1 替换为从第 21 行到第 30 行的零,对于 rest 的第 10 列也是如此。按照我的例子

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 .我非常确信我的逻辑是正确的,但是每次运行代码时,都会收到以下错误消息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.对于每一列 j,获取行索引的下限和上限并指定为 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.返回指定范围内的 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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