以下是错误声明:
EvoWithout.rb:53:in"block(2 level(in":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
要学习的一项重要技能是阅读错误消息和警告。在你的标题中,你问:
为什么我在Ruby中的一个简单矩阵加法操作中出现"无方法"错误?
但是,这不是错误消息所说的!
您不能为矩阵加法运算(Matrix#+
(获得NoMethodError
。如果你是这样的话,错误消息会说:
EvoWithout.rb:53:in `block (2 levels) in ': undefined method `+' for animal:Matrix (NoMethodError)
请注意,错误消息会说(boldemphasis mine(">动物的未定义方法`+':矩阵"(这是错误的,因为Matrix#+
存在(。然而,这并不是您的错误消息所说的。您的错误信息显示(粗体强调我的(:
nil:NilClass的未定义方法"+">
这是正确的,因为NilClass
实际上没有有+
方法,它的超类Object
、Kernel
和BasicObject
也没有。
所以,你看错了地方:你的问题不在于矩阵加法运算,你的问题是矩阵索引运算返回nil
。
原因很简单:animal
矩阵只包含一行,但要在$Behavmax + 1
行上迭代。因此,一旦$Behavmax
大于零,您就会索引到animal
的第二行,而这一行并不存在。因此,它将返回nil
,并且您的添加将失败。
请记住,对于任何运算符ω
和任意表达式a
和b
,a ω= b
等价于a = a ω b
,其中a
只求值一次,因此
animal[i,0]+= 5
大致相当于:
__temp__ = animal[i, 0]
animal[i, 0] = __temp__ + 5
如果i
不是0
,那么__temp__
将是nil
,因为animal
中只有一行。