How do I get I pass out the input parameter to ode45 integration
Afficher commentaires plus anciens
I want to integrate velocity and obtain posiiton. Is there a way to do this with ode45 and obtain the set of velocities as additonal output to the ode45. Here is a code I have written but I am not sure it works correctly.
close all; clear all;clf
x0=[0.5;0.5];
tf=5; N=10000
tspan = linspace(0, tf,N);
dt =tf/N;
[t,x]= ode45(@(t,x)position_calc(x), tspan, x0);
figure
plot(t,x(:,1),'b--','linewidth',2)
hold on
% figure
plot(t,x(:,2),'g--');
grid
legend(["x","vel","pos"])
function [dstate]= position_calc(state)
x=state(1);
dx= state(2);
vel=x^2;
dstate= [x;vel];
end
I do not want to run the function inside ode again to obtain the velocity
3 commentaires
x(:,2) is the velocity, isn't it ?
You integrate acceleration in your code. Thus what you call "vel" is acceleration, not velocity.
So dstate should be [state(2),acceleration].
If you want to integrate velocity, you have one differential equation, not two.
Hafeez Jimoh
le 31 Jan 2023
If x(:,1) is intended to be position and x(:,2) is intended to be velocity, your odes read
y''(t) = a
where "a" is acceleration.
Written as a system
y1' = y2
y2' = a
where y1 is position and y2 is velocity.
So I don't understand your function "position_calc".
Réponse acceptée
Plus de réponses (1)
There are a couple of overlooked points as Torsten pinpointed out. Here is one simple explae of dx = 2x example solution very similar to your exercise:
% Let's say: dx = 2*x; which is the velocity formulation: f(t,x) = 2*x;
% then solution x(t) can be found using dsolve() that gives an analytical
% solution or ode45 gives numerical solution
close all; clearvars
x0=0.5; % Note: dx has one Initial Condition, i.e., x(0) = 0.5, for example
tf=5; N=10000;
tspan = linspace(0, tf,N);
[t,x]= ode45(@(t,x)position_calc(x), tspan, x0);
figure
yyaxis left
plot(t,x,'bo-','linewidth',2, 'DisplayName','Displacement')
ylabel('$x(t), \ [m]$', 'Interpreter','latex')
% Now, the velocity values can be obtained from the integrated displacement values,
v =diff(x);
yyaxis right
plot(t(1:end-1),v,'r-.', 'LineWidth',1.75, 'DisplayName','Velocity');
ylabel('$v(t), \ [m/s]$', 'Interpreter','latex')
xlabel('$time, \ [s]$', 'Interpreter','latex')
grid on
legend('Show', 'Location', 'Best')
figure
D = array2table(t(1:end-1));
D = renamevars(D, 'Var1', 'time');
D.x = x(1:end-1);
D.v = v;
H=stackedplot(D, 'XVariable', 'time');
H.LineWidth=2;
H.LineProperties(1).Color = 'b';
H.LineProperties(1).Marker = 'o';
H.LineProperties(2).Color = 'r';
H.LineProperties(2).LineStyle = '-.';
grid on
function dx= position_calc(state)
dx= 2*state;
end
Catégories
En savoir plus sur Ordinary Differential Equations dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



