【发布时间】:2020-04-20 13:56:57
【问题描述】:
这是错误声明:
EvoWithout.rb:53:in `block (2 levels) in ': undefined method `+' for nil:NilClass (NoMethodError)
这是第 53 行:
if behavior[i,0] > Thrsh && s == 0 then animal[i,0]+= 5 end
以下是相关代码:
situation= Matrix[ [1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[1,0,0,0,0,1,1,1,1,1,1,0,0,0,0,1],
[1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1],
[1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1],
[1,0,0,1,1,0,1,0,1,0,1,0,1,0,0,1] ]
# Build brain with $Behavmax rows of 0,1's
brain = Matrix.build(10,16) { 1 }
for i in (0..$Behavmax)
for j in (0..$Stimmax)
if rand(4) < 1.1 then brain[i,j] = 0 end
end # j
end #i
stimulus=Matrix.column_vector([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
behavior=Matrix.row_vector([0,0,0,0,0,0,0,0,0,0])
animal=Matrix.row_vector([20,20,20,20,20,20,20,20,20,20]) # to hold value of fitness
# BEGIN MAIN PROGRAM
# Noise=20
# Go through once presenting 1 situation after another
for s in (0..4)
for j in (0..$Stimmax)
stimulus[j,0] = situation[s,j]
end # for j
# GENERATE BEHAVIOR
behavior=brain*stimulus
for i in (0..$Behavmax) #fire iff stimulus pattern matches detector
if behavior[i,0] > Thrsh && s == 0 then animal[i,0]+= 5 end
#if behavior[i,0] > Thrsh && s != 0 then print "Behavior#{i}=#{behavior[i,0]} and s=#{s} " end
end # for i
puts
end # for s
【问题讨论】:
-
animal矩阵由一行组成,所以animal[1, 0] == nil,这可能就是它发生的原因。 -
不,不是这样。将其更改为
animal[1]会出现此错误:lib/ruby/2.6.0/matrix.rb:299:in `[]': wrong number of arguments (given 1, expected 2) (ArgumentError) -
这不是重点。
animal[0, 0]返回20,就像animal[0, 1]等一样。看起来你应该有behavior[0, i]和animal[0, i]而不是behavior[i, 0]和animal[i, 0]。 -
好的,可以。但你会注意到我使用
behavior[i,0]并且它有效。确实,我复制行为来制造动物。所以没有明显的原因为什么动物不起作用。但我会尝试 -
这并不神秘。
animal和behavior矩阵每个只包含一行,所以如果你想迭代它的值,你需要迭代列,而不是行。animal[i, 0]遍历行。animal[0, i]遍历列。
标签: ruby matrix methods undefined