简体   繁体   English

在MATLAB中从2D数组创建函数(在ode45中使用)

[英]Creating a function from a 2D array in MATLAB (For use in ode45)

I am a first time MATLAB user. 我是MATLAB的第一次用户。 I have a 2d array of t vs f in MATLAB. 我在MATLAB中有2个t和f的二维数组。 This 2d array correponds to a function, say f(t). 这个二维数组对应于一个函数,即f(t)。 I am using ode45 to solve a set of differential equations and f(t) is one of the coefficients ie I have a set of equations of the form x'(t)=f(t)x(t) or variations thereof. 我正在使用ode45求解一组微分方程,而f(t)是系数之一,即我具有一组x'(t)= f(t)x(t)或其形式的方程。 How do I proceed? 我该如何进行?

I need a way to convert my array of t vs f into a function that can be used in the ode45 method. 我需要一种将t vs f数组转换为可以在ode45方法中使用的函数的方法。 Presumably, the conversion will do some linear interpolation and give me the equation of the best fit curve. 据推测,该转换将进行一些线性插值,并给出最佳拟合曲线的方程式。

Or if there is another approach, I'm all ears! 或者,如果有另一种方法,我全神贯注!

Thank you! 谢谢!

This is a simple example with passing function as a parameter to right hand side of the ODE. 这是一个简单的示例,将传递函数作为ODE右侧的参数。 Create files in the same directory and run main 在同一目录中创建文件并运行main

main.m 的main.m

t = 0:0.2:10; f = sin(t);
fun = @(xc) interp1(t, f, xc);

x0=0.5
% solve diff(x, t)=sin(t)  
% pass function as parameter                           
[tsol, xsol] = ode45(@(t, x) diff_rhs(t, x, fun),[0.0 8.0], 0.5);

% we solve equation dx/dt = sin(x), x(0)=x0
% exact solution is x(t) = - cos(t) + x(0) + 1
plot(tsol, xsol, 'x');
hold on
plot(tsol, -cos(tsol) + x0 + 1, '-');
legend('numerical', 'exact');

diff_rhs.m diff_rhs.m

function dx = diff_rhs(t, x, fun)
  dx = fun(t);
end

References in the documentation: interp1 and anonymous Functions . 文档中的参考: interp1匿名函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM