Writing a system of ODEs for ode45
조회 수: 7 (최근 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!