spring mass using ode45

3 ビュー (過去 30 日間)
リッディ チャワン
リッディ チャワン 2021 年 11 月 18 日
編集済み: VBBV 2023 年 5 月 28 日
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

回答 (1 件)

Alan Stevens
Alan Stevens 2021 年 11 月 18 日
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

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by