Solve 2nd order ODE using Euler Method

VERY new to Matlab...
Trying to implement code to use Euler method for solving second order ODE.
Equation:
x'' + 2*z*w*x' + w*x = 2*sin(2*pi*2*t)
z and w are constants. "t" is time.
Any help would be great.
Thanks!

댓글 수: 5

John D'Errico
John D'Errico 2022년 9월 27일
편집: John D'Errico 2022년 9월 27일
If you need to solve that ODE, then why in the name of god are you writing an Euler's method to solve the ODE. Use ODE45. Do not write your own code. Since the only reason you need to use Euler's method is to do this as a homework assignment, then you need to write your own code. But Answers is not a service where we do your homework with no effort shown by you.
Matt
Matt 2022년 9월 27일
This is a HW assignment. No need to be a jerk about it. If you don't want to help then don't post.
Matt
Matt 2022년 10월 4일
이동: James Tursa 2022년 10월 4일
So, I've been going at it a different way but still getting errors...
%Euler solution for ODE function
HW2_Parameters % Load initial conditions into the workspace
t0 = 0 ;
n1 = (tn-t0)/h ;
for i=1:n1
t(i+1) = t0 + i*h ;
x_dd(i) = (2*sin(2*pi*2*t(i))) - (2*zeta*omega_n*x_d(i-1)) - (omega_n*x(i-1));
x_d(i) = x_d(i-1) + (x_dd(i)*h);
x(i) = x(i-1) + (x_d(i)*h);
end
Any thoughts?
James Tursa
James Tursa 2022년 10월 4일
@Matt - FYI, when you get errors, it is best to post the entire error message along with your code. Regardless, see my answer below ...
Matt
Matt 2022년 10월 4일
Will do. Really new here so just learning the ways about this. I'll be back! :-)

댓글을 달려면 로그인하십시오.

 채택된 답변

James Tursa
James Tursa 2022년 10월 4일
편집: James Tursa 2022년 10월 4일

0 개 추천

You start your loop with i=1, but that means your x_d(i-1) will be x_d(0), an invalid index, hence the error. You need to set initial values for x_d(1) and x(1), and then have your starting loop index be 2. E.g.,
x(1) = initial x value
x_d(1) = initial xdot value
for i=2:n1 % start loop index at 2
x_dd(i-1) = use (i-1) indexes on everything on rhs
x_d(i) = use (i-1) indexes on everything on rhs
x(i) = use (i-1) indexes on everything on rhs

추가 답변 (1개)

Davide Masiello
Davide Masiello 2022년 9월 27일
편집: Davide Masiello 2022년 9월 27일

0 개 추천

Hi Matt - a second order ODE can be decomposed into two first order ODEs.
The secret is to set 2 variables y as
The you have
An example code is
clear,clc
tspan = [0,1]; % integrates between times 0 and 1
x0 = [1 0]; % initial conditions for x and dx/dt
[t,X] = ode15s(@odeFun,tspan,x0); % passes functions to ODE solver
x = X(:,1);
dxdt = X(:,2);
plot(t,x)
function dydt = odeFun(t,y)
z = 1;
w = 1;
dydt(1,1) = y(2);
dydt(2,1) = 2*z*w*y(2)-w*y(1)+2*sin(2*pi*2*t);
end

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

제품

릴리스

R2022b

질문:

2022년 9월 27일

댓글:

2022년 10월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by