首页 > 解决方案 > Writing lambda in MATLAB

问题描述

I am trying to convert this code into MATLAB but I am not sure how to do the subscripts (Y[i] = Y[i-1]) as well as the func and f_exact variables heres the code:

def Forward_Euler(y0,t0,T,dt,f):
    t = np.arange(t0,T+dt,dt)
    Y = np.zeros(len(t))
    Y[0] = y0
    for i in range(1,len(t)):
        Y[i] = Y[i-1]+dt*f(Y[i-1], t[i-1])
    return Y, t
    
func = lambda y,t: y-t
f_exact = lambda t: t+1-1/2*np.exp(t)

标签: pythonmatlabfunction

解决方案


您可以在 matlab中使用匿名函数:

func = @(y,t)(y - t)
f_exact = @(t)(t + 1 - exp(t)/2) % it works with any matrix t as well

你也可以使用矩阵(它们应该保持矩阵运算规则)。例如,在funcfunction中,由于function的形式有一个负号,所以y和的维数t必须相同。


推荐阅读