spring mass using ode45

2 views (last 30 days)
リッディ チャワン
リッディ チャワン on 18 Nov 2021
Edited: VBBV on 28 May 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

Answers (1)

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

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!