spring mass using ode45

3 visualizzazioni (ultimi 30 giorni)
リッディ チャワン
リッディ チャワン il 18 Nov 2021
Modificato: VBBV il 28 Mag 2023
I wrote this program for solving a spring mass equation using ode45 but it shows an error at the ode45
M = 1.0;
K = 10;
C = 1;
l = 0.5;
g = 9.8;
x0 = [0;
0];
tspan = [0, 10];
[t, x] = ode45(@func, tspan, x0);
subplot(2,1,1)
plot(t, x(:, 1));
grid('on');
%axis([0 10 -1 1]);
xlabel('time [s]');
ylabel('x [m]');
subplot(2,1,2)
plot(t, x(:, 2));
grid('on');
%axis([0 10 -1 1]);
xlabel('time [s]');
ylabel('$\dot{x}$ [m/s]');
% 導関数の定義
function xdot = func(t, x)
M = 1.0;
K = 10;
C = 1;
l = 0.5;
g = 9.8;
xdot = [x(2);
-K*(x-l)*x(1)/M-C*x(2)/M+g]*dt;
end

Risposte (1)

Alan Stevens
Alan Stevens il 18 Nov 2021
Like this
x0 = [0;
0];
tspan = [0, 10];
[t, x] = ode45(@func, tspan, x0);
subplot(2,1,1)
plot(t, x(:, 1));
grid('on');
%axis([0 10 -1 1]);
xlabel('time [s]');
ylabel('x [m]');
subplot(2,1,2)
plot(t, x(:, 2));
grid;
%axis([0 10 -1 1]);
xlabel('time [s]');
ylabel('dx/dt [m/s]');
function xdot = func(~, x)
M = 1.0;
K = 10;
C = 1;
l = 0.5;
g = 9.8;
xdot = [x(2);
-K*(x(1)-l)*x(1)/M-C*x(2)/M+g]; % x(1) not just x. No need for dt
end

Categorie

Scopri di più su Programming 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!

Translated by