我被一个简单的增量函数卡住了
from numpy import *
from pylab import *
## setup parameters and state variables
T = 1000 # total time to simulate (msec)
dt = 1 # simulation time step (msec)
time = arange(0, T+dt, dt) # time array
Vr = -70 #reset
El = -70
## LIF properties
Vm = zeros(len(time)) # potential (V) trace over time
Rm = 10 # resistance (mOhm)
tau_m = 10 # time constant (msec)
Vth = -40 # spike threshold (V)
## Input stimulus
I = 3.1 # input current (nA)
Vm[0] = -70
Fr = 0
## iterate over each time step
def func(Ie, Vm, Fr):
for i, t in enumerate(time):
if i == 0:
Vm[i] = -70
else:
Vm[i] = Vm[i-1] + (El- Vm[i-1] + Ie*Rm) / tau_m * dt
if Vm[i] >= Vth:
Fr += 1
Vm[i] = El
return
Ie = 3.1
func( Ie, Vm, Fr)
print Fr
## plot membrane potential trace
plot(time, Vm)
title('Leaky Integrate-and-Fire')
ylabel('Membrane Potential (mV)')
xlabel('Time (msec)')
ylim([-70,20])
show()
为什么在调用func之后Fr仍然为0?
我知道这很简单,但是我为此花了很长时间
谢谢
python大神给出的解决方案
您有两个在不同范围内的Fr变量
Fr = 0
是您功能之外的,因此永不改变。
Fr += 1
在函数内部,将被递增,但这是一个不同的变量。
这是解决方案(可能的一种):
def func(Ie, Vm, Fr):
for i, t in enumerate(time):
if i == 0:
Vm[i] = -70
else:
Vm[i] = Vm[i-1] + (El- Vm[i-1] + Ie*Rm) / tau_m * dt
if Vm[i] >= Vth:
Fr += 1
Vm[i] = El
return Fr
然后,做
Fr = func(Ie, Vm, Fr)
另一个提示。
如果默认情况下Fr
变量始终为0,则可以执行以下操作:
def func(Ie, Vm, Fr=0):
定义函数时,仅当您需要不同于0的值时才传递第三个参数。