[英]how to get dy/dt in ode45 matlab
I have 2 relations: 我有2个关系:
y=y0+V*t+sin(w*t) #relation1
dy/dt=(current/P)-(M1/P)*sin(y)+(M2/P)*sin(y+E)+U*cos(y)*sin(w*t) #relation2
(M1,P,M2,E,w & U are numerical constants) My goal is to find V(voltage) for different currents. (M1,P,M2,E,w和U是数值常数)我的目标是找到不同电流的V(电压)。 in order to do that, I have to solve relation 2 numerically for different currents, and get dy/dt and then by using the relation between y and V which is <∂y/∂t>=V (<....> denotes a time average), I have to find V. consider that I don`t know the value of dy/dt. 为了做到这一点,我必须对不同的电流数值地求解关系2,并得到dy / dt,然后使用y和V之间的关系,即<∂y/∂t> = V(<.......表示时间平均),我必须找到V。考虑到我不知道dy / dt的值。 I tried this 我试过了
current = 6e-7 : 1e-8 : 8.5e-7;
for k=1:length(current)
f = @(y, t, M1, P, M2, E) (current(k)/P)-(M1/P)*sin(y)+(M2/P)*sin(y+E)+U*cos(y)*sin(w*t);
[t{k}, y{k}] = ode45(f,tspan,y0);
end
this gives me y for different currents in a cell. 这给了我一个单元中不同电流的y。
I found out that the following code will give me dy/dt: 我发现以下代码将给我dy / dt:
ydot=y(:,2) #if I use 1 instead of 2 it will give me y)
but Now, my problem is changed to this: when I use this code, It will give me dy/dt only for 1 current, how can I get dy/dt for different currents? 但是现在,我的问题变成了这样:当我使用此代码时,仅给1电流提供dy / dt,如何获得不同电流的dy / dt?
Try making your output a vector, where the first element is the state that you are interested in ( y
), and the second element is its derivative with respect to time ( dy/dt
); 尝试使输出成为向量,其中第一个元素是您感兴趣的状态( y
),第二个元素是其相对于时间的导数( dy/dt
); so y0 = [0;0];
所以y0 = [0;0];
or whatever your starting conditions are. 或您的起始条件如何。 Then make a separate file for your ODE, let's call it "myFcn": 然后为您的ODE制作一个单独的文件,我们将其称为“ myFcn”:
function dydt = myFcn(~, y, M1, P, M2, E, current) % the ~ is because we are not explicitly dependent on tspan
% Initialize the d/dt vector of our states, y
dydt = zeros(size(y));
% Update the d/dt vector of our states
dydt(1) = y(2); % because (d/dt)y(1) = y(2) = dydt
dydt(2) = current/P - (M1/P)*sin(y) + (M2/P)*sin(y+E); % your update equation
Now just replace your handle and ode45
call in the above with: 现在,只需将上面的handle和ode45
调用替换为:
f = @(y, M1, P, M2, E, current(k))myFunc(y, M1, P, M2, E, current(k));
[t{k}, y{k}] = ode45(f, tspan, y0);
Your output will then be the vector y
that will give your "position" state y(1)
and "velocity" state y(2)
. 然后,您的输出将是向量y
,该向量y
将给出“位置”状态y(1)
和“速度”状态y(2)
。 These will be stored in your cell array as before. 这些将像以前一样存储在您的单元格数组中。
Updated code to include current(k)
, remaining consistent with OP's code. 更新了代码以包括current(k)
,与OP的代码保持一致。
如果您只是想区分,可以使用f2 = jacobian(f,[dt])和matlabfunction(f2)来获取函数句柄...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.