how I can fix sample time in ode45

3 次查看(过去 30 天)
I want to fix the sample time (for example, T=0.5) in ode45. How can I do it? If it is not possible, do we have another way to fix the sample time in Matlab?
tspan = 0:1:10000;
y0 = [0.2,0.3];
[t,y] = ode45(@(t,y) odefcn(t,y), tspan, y0);
%
function dx = odefcn(t,x)
dx = zeros(2,1);
u=[2 -2]*x(1:2)+1;
dx(1)=x(1)-2*x(2)
dx(2)=-x(2)+u
end

采纳的回答

Sam Chak
Sam Chak 2023-10-29
Are you looking for something like this?
T = 0.5;
tspan = 0:T:10;
y0 = [0.2,0.3];
[t, y] = ode45(@(t,y) odefcn(t,y), tspan, y0);
plot(t, y, '-o'), grid on
xlabel('Time')
%
function dx = odefcn(t,x)
dx = zeros(2,1);
u = [2 -2]*x(1:2) + 1;
dx(1) = x(1) - 2*x(2);
dx(2) = - x(2) + u;
end
  3 个评论
Sam Chak
Sam Chak 2023-10-29
Indeed, ode45() solver employs its own internal steps for computing the solution and subsequently assesses the solution at the designated points in tspan. Nonetheless, it is crucial to emphasize that the solutions generated at the specified points exhibit the same level of accuracy as the solutions computed at each internal step. Another approach is to use deval().
tspan = [0, 10];
y0 = [0.2, 0.3];
sol = ode45(@(t,y) odefcn(t,y), tspan, y0);
T = 0.5;
t = 0:T:10;
y = deval(sol, t);
plot(t, y, '-o'), grid on
xlabel('Time')
function dx = odefcn(t,x)
dx = zeros(2,1);
u = [2 -2]*x(1:2) + 1;
dx(1) = x(1) - 2*x(2);
dx(2) = - x(2) + u;
end
Sam Chak
Sam Chak 2023-10-29
Else everything fails, you can write a simple algorithm using the convetional Runge–Kutta solver that allows the fixed step size for the integration..
h = 0.5;
x = 0:h:10;
% Initial values
y(:,1) = [0.2 0.3];
% Input signal
u = @(y) [2 -2]*y + 1;
% State equations
odefcn = @(t, y) [y(1) - 2*y(2);
- y(2) + u(y)];
% Runge-Kutta ODE Solver
for i = 1:(length(x)-1)
k1 = odefcn(x(i), y(:,i));
k2 = odefcn(x(i)+0.5*h, y(:,i)+0.5*h*k1);
k3 = odefcn(x(i)+0.5*h, y(:,i)+0.5*h*k2);
k4 = odefcn(x(i)+h, y(:,i)+k3*h);
y(:,i+1) = y(:,i) + (h/6)*(k1 + 2*k2 + 2*k3 + k4);
end
plot(x, y, '-o'), grid on
xlabel('Time')

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
Walter Roberson 2023-10-29
You cannot do that. ode45() is always a variable-step solver. So is ode15s, ode23s, ode78, ode113, ode89.

类别

Help CenterFile Exchange 中查找有关 Ordinary Differential Equations 的更多信息

标签

产品


版本

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by