本文介绍了MATLAB:如何将参数传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下功能:
函数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函数:
[ty] = ode45(@ypdiff,[to tf],yo);
但是如果我想将一个参数传递给这个函数,我将如何使用ode45函数?具体来说,我正在尝试以下形式:
pre $函数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)]';
解决方案
您可以使用在matlab中(类似于其他语言中的lambda函数) p>
u = 1.2;
[t y] = ode45(@(t,y)ypdiff(t,y,u),[to tf],yo);
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)]';
解决方案
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);
这篇关于MATLAB:如何将参数传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!