在求解ode时,我如何使用匿名函数来传递参数,而不是在matlab中创建两个m.文件



我想把这两个文件合并成一个m.file,而不是使用函数来定义带有传递参数的"monod",我想使用匿名函数传递参数。因此,要实现这两个文件的合并。

%(file 1)
function dcdt = monod(t,c,k,ks,y,b)
dcdt = zeros(2,1);
dcdt(1) = -k*c(2)*c(1)/(ks+c(1));
dcdt(2) = y*k*c(2)*c(1)/(ks+c(1))-b*c(2);
% (file 2) ODE45
k = 3.7;ks=30;y=0.03;b=0.01;
options = odeset('Reltol',1.e-10,'AbsTol',1.e-10);
[t,c] = ode45(@monod, [0,200],[200,1],options,k,ks,y,b);
% plot 
C = c(:,1);
Xa = c(:,2);
figure(1);
grid on;
subplot(2,1,1);
plot(t,C);
title('Substrate aqueous concentration vs time(ODE45)');
xlabel('time');ylabel('Substrate aqueous concentration C')
subplot(2,1,2);
plot(t,Xa);
title('Active-cell concentration vs time');
xlabel('time');ylabel('Active-cell concentration Xa(ODE45)');

您可以简单地在文件中定义一个嵌套函数。完全可以接受的语法。但是,您需要使文件#2成为一个实际的函数,因为您不能用脚本文件定义嵌套函数。要做到这一点,只需使它成为一个不接受输入也不返回任何内容的函数。:

function run_ode %// Change here
    %// Include monod function here - watch the end keyword
    function dcdt = monod(t,c,k,ks,y,b)
        dcdt = zeros(2,1);
        dcdt(1) = -k*c(2)*c(1)/(ks+c(1));
        dcdt(2) = y*k*c(2)*c(1)/(ks+c(1))-b*c(2);
    end %<----
%// Begin File #2
k = 3.7;ks=30;y=0.03;b=0.01;
options = odeset('Reltol',1.e-10,'AbsTol',1.e-10);
[t,c] = ode45(@monod, [0,200],[200,1],options,k,ks,y,b);
% plot 
C = c(:,1);
Xa = c(:,2);
figure(1);
grid on;
subplot(2,1,1);
plot(t,C);
title('Substrate aqueous concentration vs time(ODE45)');
xlabel('time');ylabel('Substrate aqueous concentration C')
subplot(2,1,2);
plot(t,Xa);
title('Active-cell concentration vs time');
xlabel('time');ylabel('Active-cell concentration Xa(ODE45)');
end %// Take note of this end too as we now have nested functions

将上述代码复制粘贴到名为run_ode.m的文件中,然后在MATLAB命令提示符中输入run_ode并按ENTER

>> run_ode

你应该得到你想要的结果。


或者,如果您想使用问题标题中引用的匿名函数,您可以这样做:

%// Change here
monod = @(t,c,k,ks,y,b) [-k*c(2)*c(1)/(ks+c(1)); y*k*c(2)*c(1)/(ks+c(1))-b*c(2)];
k = 3.7;ks=30;y=0.03;b=0.01;
options = odeset('Reltol',1.e-10,'AbsTol',1.e-10);
[t,c] = ode45(monod, [0,200],[200,1],options,k,ks,y,b); %// Change here too
% plot 
C = c(:,1);
Xa = c(:,2);
figure(1);
grid on;
subplot(2,1,1);
plot(t,C);
title('Substrate aqueous concentration vs time(ODE45)');
xlabel('time');ylabel('Substrate aqueous concentration C')
subplot(2,1,2);
plot(t,Xa);
title('Active-cell concentration vs time');
xlabel('time');ylabel('Active-cell concentration Xa(ODE45)');

monod现在是一个匿名函数,它接受6个输入,并输出一个两元素列向量供ode45使用。请注意,ode45现在已更改,因此@已被删除。monod现在已经是一个匿名函数的句柄,所以不需要使用@

最新更新