全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 R语言论坛
24273 8
2015-12-08
以下是我的程序代码:
S<-matrix(100,10,13)
ran<-matrix(runif(12,0,1),10,12)
for(i in 2:13){
  for(j in 1:10){
    if(ran[i-1,j]<0.45){
      S[i,j]<-1.1*S[i-1,j]
    }else if(ran[i-1,j]<0.65){
        S[i,j]<-S[i-1,j]
    }else{
        S[i,j]<-0.9*S[i-1,j]
      }
  }
}

运行后报错:
Error in `[<-`(`*tmp*`, i, j, value = 130.45131) :
  subscript out of bounds

真心求助各位大神错在什么地方
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2015-12-8 00:48:00
As you can see you have:
length(2:13)
[1] 12

however:
dim(ran)
[1] 10 12

dim(S)
[1] 10 13

You see? i iterates from 2:13, which is larger than both dim(ran)[1] and dim(S)[1]  

I think you should be able to fix the code now.

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2015-12-8 01:01:45
neuroexplorer 发表于 2015-12-8 00:48
As you can see you have:
length(2:13)
[1] 12
Thank you!
I think I put i and j at wrong places in my 'for sentences'. = =
But after I switched i and j, it remains wrong.
It says 'Error in if (ran[i - 1, j] < 0.45) { : argument is of length zero'.
Could you please tell me how to solve this new problem?
Thank you very much.
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2015-12-8 01:13:21
neuroexplorer 发表于 2015-12-8 00:48
As you can see you have:
length(2:13)
[1] 12
I know how to solve this problem now.
And this is the fixed code:
S<-matrix(100,10,13)
ran<-matrix(runif(12,0,1),10,12)
for(i in 1:10){
  for(j in 2:13){
    if(ran[i,j-1]<0.45){
      S[i,j]<-1.1*S[i,j-1]
    }else if(ran[i,j-1]<0.65){
        S[i,j]<-S[i,j-1]
    }else{
        S[i,j]<-0.9*S[i,j-1]
      }
  }
}

Thank you.
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2015-12-8 01:21:02
Here you go:

S<-matrix(100,10,13)
ran<-matrix(runif(12,0,1),10,12)
for(j in 2:13){
  for(i in 1:10){
    if(ran[i,j-1]<0.45){
      S[i,j]<-1.1*S[i,j-1]
    }else if(ran[i,j-1]<0.65){
      S[i,j]<-S[i,j-1]
    }else{
      S[i,j]<-0.9*S[i,j-1]
    }
  }
}
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2015-12-8 01:25:47
also, you do not have to use loop here. You can use logic indexing, instead. The latter is a lot faster than loop.

suppose:

m <- matrix(runif(12), nrow = 3)
> m
          [,1]      [,2]      [,3]      [,4]
[1,] 0.2790982 0.8438885 0.7953321 0.2782153
[2,] 0.9958075 0.6737918 0.0568551 0.7749910
[3,] 0.1693278 0.3926015 0.8945651 0.7571608

m[m > 0.5]  = 1
> m
          [,1]      [,2]      [,3]      [,4]
[1,] 0.2790982 1.0000000 1.0000000 0.2782153
[2,] 1.0000000 1.0000000 0.0568551 1.0000000
[3,] 0.1693278 0.3926015 1.0000000 1.0000000
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

点击查看更多内容…
相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群