Usage of ode function
5 次查看(过去 30 天)
显示 更早的评论
So I need to find the values for dv/dt and the dr/dt, the first derivate of the functions. The problem is every else variable is a vector in a form nx1,
and i have different values for every variable depending of time. How do I use properly the ode function to get the solution?
0 个评论
回答(2 个)
Jon
2024-1-23
编辑:Jon
2024-1-23
Here is one approach, see https://www.mathworks.com/help/optim/ug/passing-extra-parameters.html for further details on passing extra parameters.
This example is just intended to give you an idea of how to approach this. You will have to modify it based on your needs, and actual values
% Make up some values just to demonstrate program
m = 1;
I = 2;
a = 8;
b = 5;
u = 4;
nPts = 100;
tFinal = 23;
ty = linspace(0,tFinal,nPts);
Fyf = randn(nPts,1); % time varying force Fyf
Fyr = randn(nPts,1); % time varying force Fyr
v0 = 0; % initial velocity
r0 = 0; % initial position
[t,v,r] = mySolve(m,I,a,b,u,ty,Fyf,Fyr,v0,r0);
plot(t,v,t,r);
legend('v','r')
ylabel('position and velocity')
xlabel('time')
% Everything below this line could be put into a separate file
function [t,v,r] = mySolve(m,I,a,b,u,ty,Fyf,Fyr,v0,r0)
%motionSolve - solves my system of ode's
% m,I,a,b,u - System parameters (assumed to be scalar constants)
% ty - vector of time values where forces are defined
% Fyf,Fyr - vectors of force values occuring at times corresponding to
% elements of ty
% Find start and end time
tspan = [min(ty),max(ty)];
% Set initial condition
x0 = [v0,r0];
% Solve ode
[t,x] = ode45(@odefun,tspan,x0);
% Return desired values
v = x(:,1);
r = x(:,2);
% Use nested function so that external inputs, Fyf and Fyr and parameters
% are in scope when computing derivative values
function dxdt = odefun(t,x)
% Calculates derivatives with respect to time
% Interpolate to find force values at current time
ff = interp1(ty,Fyf,t);
fr = interp1(ty,Fyr,t);
% Assign local variable names for readability
v = x(1);
r = x(2);
% Calculate derivatives
dxdt(1,1) = 1/m*(ff + fr ) - u*r;
dxdt(2,1) = 1/I*(a*ff - b*fr);
end
end
1 个评论
Jon
2024-1-23
@Torsten exploits the special structure of your ode's in which dr/dt is only a function of the external inputs, so you can just integrate to obtain r(t). Since dv/dt depends only on r(t), and the external inputs (but not upon v(t)) you can then just integrate to find v(t).
The approach I have is more general, and would work for ode's that can not be directly integrated and require a solver such as ode45
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Ordinary Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!