spring mass using ode45

4 vues (au cours des 30 derniers jours)
リッディ チャワン
リッディ チャワン le 18 Nov 2021
Modifié(e) : VBBV le 28 Mai 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

Réponses (1)

Alan Stevens
Alan Stevens le 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

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by