spring mass using ode45

4 Ansichten (letzte 30 Tage)
リッディ チャワン
リッディ チャワン am 18 Nov. 2021
Bearbeitet: VBBV am 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

Antworten (1)

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

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by