MATLAB:如何将参数传递给函数?

发布于 2024-08-21 13:16:48 字数 619 浏览 4 评论 0原文

我有以下函数:

function ypdiff = ypdiff(t,y)
    a = 0.01;
    b = 0.1;
    ypdiff(1) = -a*y(1)*y(2);
    ypdiff(2) = b*y(1)*y(2)-b*y(2);
    ypdiff(3) = b*y(2);
    ypdiff = [ypdiff(1) ypdiff(2) ypdiff(3)]';

如果我想解决这个问题,我将调用 ode45 函数,如下所示:

[t y] = ode45(@ypdiff, [to tf], yo);

但是如果我想向该函数传递参数,我将如何使用 ode45 函数?具体来说,我正在尝试以下公式:

function ypdiff = ypdiff(t,y,u)
    a = 0.01;
    b = 0.1;
    ypdiff(1) = -a*u*y(1)*y(2);
    ypdiff(2) = b*u*y(1)*y(2)-b*y(2);
    ypdiff(3) = b*u*y(2);
    ypdiff = [ypdiff(1) ypdiff(2) ypdiff(3)]';

I have the following function:

function ypdiff = ypdiff(t,y)
    a = 0.01;
    b = 0.1;
    ypdiff(1) = -a*y(1)*y(2);
    ypdiff(2) = b*y(1)*y(2)-b*y(2);
    ypdiff(3) = b*y(2);
    ypdiff = [ypdiff(1) ypdiff(2) ypdiff(3)]';

If I want to solve this, I would call the ode45 function as follows:

[t y] = ode45(@ypdiff, [to tf], yo);

But if I want to pass a parameter to this function, how would I use the ode45 function? Specifically, I am trying for the following formulation:

function ypdiff = ypdiff(t,y,u)
    a = 0.01;
    b = 0.1;
    ypdiff(1) = -a*u*y(1)*y(2);
    ypdiff(2) = b*u*y(1)*y(2)-b*y(2);
    ypdiff(3) = b*u*y(2);
    ypdiff = [ypdiff(1) ypdiff(2) ypdiff(3)]';

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

打小就很酷 2024-08-28 13:16:48

您可以在matlab中使用匿名函数 (类似于其他语言中的 lambda 函数):

u = 1.2;
[t y] = ode45(@(t, y) ypdiff(t, y, u), [to tf], yo);

You can use an anonymous function in matlab (similar to lambda functions in other languages):

u = 1.2;
[t y] = ode45(@(t, y) ypdiff(t, y, u), [to tf], yo);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文