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
댓글 수: 0
채택된 답변
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
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
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
2023년 10월 29일
You cannot do that. ode45() is always a variable-step solver. So is ode15s, ode23s, ode78, ode113, ode89.
If you need a fixed step solver then see https://www.mathworks.com/matlabcentral/answers/98293-is-there-a-fixed-step-ordinary-differential-equation-ode-solver-in-matlab-8-0-r2012b#answer_107643
댓글 수: 0
참고 항목
카테고리
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!