python - 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)
解决方案
您可以在 matlab中使用匿名函数:
func = @(y,t)(y - t)
f_exact = @(t)(t + 1 - exp(t)/2) % it works with any matrix t as well
你也可以使用矩阵(它们应该保持矩阵运算规则)。例如,在func
function中,由于function的形式有一个负号,所以y
和的维数t
必须相同。
推荐阅读
- android - 重新加载应用程序后更新全局变量
- java - 如何在流 API 中处理 InterruptedException 和 ExecutionException
- python - 有没有办法拆分字典键的值?
- variables - 如何将包级变量值映射到 SSIS 中的项目参数?
- amazon-web-services - Cloud Formation 不创建 API 网关
- python - 未在具有成本层的分配策略范围内创建变量
- java - 如何在 Spring 中使用 Ehcache 中的 BlockingCache?
- javascript - 如何使用material-ui处理“外部”单击对话框(模态)
- c# - 将一个 WPF ListView 的项目与相对于另一个 ListView 中项目的最终布局的位置对齐
- azure-devops - 使用 yml 和服务连接时,构建代理中未下载的 git 工件