Writing a system of ODEs for ode45
10 ビュー (過去 30 日間)
古いコメントを表示
Hi,
I wrote a .m-file that has three second-order differential equations, broken down into six first-order equations.
When I run the code, I get the error message, "Unrecognized function or variable 'y'.
Here's the beginning of my code file:
x = y(1);
y = y(2);
theta = y(3);
vx = y(4);
vy = y(5);
omega = y(6);
g = 9.81; % gravitational acceleration
Another question is: should I write a function file, or use anonymous function handles?
Thanks!
1 件のコメント
Paul
2023 年 9 月 24 日
Hi Noob,
You're more likely to get an answer if you post the complete code and the error message. From what's shown
x = y(1);
y = y(2); % <- problem here
theta = y(3);
vx = y(4);
vy = y(5);
omega = y(6);
g = 9.81; % gravitational acceleration
there will be a problem after the indicated line because y is being reassigned as a scalar value from y(2), but the next line references y(3) for the assignment to theta. But, based on the error message it sounds like you're having a different error before you get to this portion of the code.
回答 (1 件)
Sam Chak
2023 年 9 月 24 日
Your code is unfinished, and when you run it, MATLAB will throw an error message. You can also try solving the ODE by creating an ode object function. See example below. This method was introduced in release R2023b. For more information, please check out this link:
F = ode;
F.Parameters = 9.81;
F.ODEFcn = @(t, y, g) [y(4); % dx/dt
y(5); % dy/dt
y(6); % dtheta/dt
- y(4) - g*sin(y(1)) % dvx/dt
- y(5) - g*sin(y(2)) % dxy/dt
- y(6) - g*sin(y(3))]; % domega/dt
F.InitialValue = [3 2 1 0 0 0]; % x0, y0, theta0, vx0, vy0, omega0
% F.Solver = "ode45"; % default automatically selects a solver
sol = solve(F, 0, 10); % solve ode in the time interval from 0 to 10
% Plotting the results
plot(sol.Time, sol.Solution), grid on
legend({'$x$', '$y$', '$\theta$', '$v_{x}$', '$v_{y}$', '$\omega$'}, 'interpreter', 'latex', 'fontsize', 12, 'location', 'southeast')
xlabel('Time (seconds)')
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Ordinary Differential Equations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!