使用Matlab中的循环生成变量

问题描述 投票:-1回答:2

我正在尝试将程序从Matlab转换为Python。

在Python中我写道:

age=np.arange(start_age, start_age+D, deltat)
For num in age:        
if age[:]<(65):
    Y=1
    break
else
    Y=0
    break
    break
H = (1/r) * (1 - math.exp(-r * max(0, (65 - age[:])))
A = ((1 - theta) * r - rho) / theta + 0.5 * ((1 - theta) / theta ** 2) *(    _lambda **2)
g = (1/A) * (math.exp(A * (D - (age[:] - start_age))) - 1)

我想要做的是以下内容:

  • 对于age我需要一系列从20到79的整数;
  • 对于Y我需要为年龄的每一个价值, 对于小于65的数字,我需要1和 对于每个大于或等于65的数字,我需要一个0。
  • HAg只是功能。

我有两个问题:

  1. 它不允许我使用age中的值。
  2. Y的循环不起作用。
python loops numpy for-loop if-statement
2个回答
0
投票

听起来像这是你想要的ageY

In [314]: age = np.arange(20,80,5)
In [315]: Y = np.where(age<65, 1, 0)
In [316]: age
Out[316]: array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75])
In [317]: Y
Out[317]: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0])

对于其余的,我不会尝试测试代码(太多未定义的变量),但我认为这将起作用(对于标量参数):

H = (1/r) * (1 - np.exp(-r * max(0, (65 - age)))
A = ((1 - theta) * r - rho) / theta + 0.5 * ((1 - theta) / theta ** 2) * (_lambda **2)
g = (1/A) * (np.exp(A * (D - (age - start_age))) - 1)

math.exp用于标量值,np.exp用于数组。


测试有限:

In [318]: H = (1-np.exp(max(0, 65-age)))
----------------------------------------------------------------------
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

哎呀,错误的max。这是Python标量之一:

In [319]: H = (1-np.exp(np.maximum(0, 65-age)))
In [320]: H
Out[320]: 
array([ -3.49342711e+19,  -2.35385267e+17,  -1.58601345e+15,
        -1.06864746e+13,  -7.20048993e+10,  -4.85165194e+08,
        -3.26901637e+06,  -2.20254658e+04,  -1.47413159e+02,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00])
In [321]: g = np.exp((1-(age-20)))
In [322]: g
Out[322]: 
array([  2.71828183e+00,   1.83156389e-02,   1.23409804e-04,
         8.31528719e-07,   5.60279644e-09,   3.77513454e-11,
         2.54366565e-13,   1.71390843e-15,   1.15482242e-17,
         7.78113224e-20,   5.24288566e-22,   3.53262857e-24])

0
投票

试试这个:

for num in age:
   if num < 65:
     Y=1
     break
   else:
     Y=0
     break
H = (1/r) * (1 - math.exp(-r * max(0, (65 - age[:])))
A = ((1 - theta) * r - rho) / theta + 0.5 * ((1 - theta) / theta ** 2) *(    
_lambda **2)
g = (1/A) * (math.exp(A * (D - (age[:] - start_age))) - 1)# equation (A11)

如果您像这样使用for循环,那么您可以使用数字而不是年龄来使用列表中的每个元素!

但:

你使用喙的方式,你总是停在阵列的第一个元素并纠正我,如果我错了,但我不认为这是你想要的...所以或你失去了休息或你可以只是检查第一个元素,如下所示:

if age[0] < 65:
© www.soinside.com 2019 - 2024. All rights reserved.