how I can fix sample time in ode45
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
hossen hassanzadth
il 29 Ott 2023
Risposto: Walter Roberson
il 29 Ott 2023
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 Commenti
Risposta accettata
Sam Chak
il 29 Ott 2023
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 Commenti
Sam Chak
il 29 Ott 2023
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
il 29 Ott 2023
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')
Più risposte (1)
Walter Roberson
il 29 Ott 2023
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 Commenti
Vedere anche
Categorie
Scopri di più su Ordinary Differential Equations in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!