euler's method
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
taojian li
am 20 Nov. 2021
Bearbeitet: James Tursa
am 20 Nov. 2021
I am trying to solve a equation but the dydt is wrong I guess? The original equation is y''+0.1y'+siny=0
h = 0.01;
x = 0:h:10;
y = zeros(size(x));
y(1) = 1;
n = numel(y);
for i = 1:n-1
dy = -0.1*y(2)+siny(1);
y(i+1) = y(i) + dy*h;
end
0 Kommentare
Akzeptierte Antwort
Yongjian Feng
am 20 Nov. 2021
What is siny? Is it sin(y)?
Also you dy is a constant in the loop, only depends on y(2) and y(1). Maybe it should depend on y(i) instead?
2 Kommentare
Weitere Antworten (1)
James Tursa
am 20 Nov. 2021
Bearbeitet: James Tursa
am 20 Nov. 2021
Your code does not have enough states. You have a 2nd order ODE (the highest derivative present is 2), so the state vector needs to be two elements, not one element as you have it. You will need to carry both y and y' at each step. To keep with your outline, let's make the state a column vector, and then have the result in a matrix where the columns are the states at each time point. I.e., y(1,i) is the y at time x(i), and y(2,i) is the y' at time x(i). Then take your code and everywhere you see y you need to replace it with a column vector. E.g.,
h = 0.01;
x = 0:h:10;
y = zeros(2,numel(x)); % y is a matrix composed of 2-element column vector states
y(:,1) = [1;yprime_initial]; % the first column is the initial state for y and y'
n = numel(x); % changed argument to x
for i = 1:n-1
dy = [ y' at time x(i); y'' at time x(i) ]; % A 2-element column vector, you need to fill this in
y(:,i+1) = y(:,i) + dy*h; % changed the y to column vectors
end
I modified almost everything in your code to account for the 2-element column vector states. I even included the outline of what the 2-element column vector dy needs to be in terms of y' and y''. You simply need to fill in the values for these. It will be a function of the current column vector state y(:,i) and time x(i). Give it a shot and let us know if you have problems. I have arbitrarily given the inital y' value as yprime_initial, but you should change this to the actual value.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Numerical Integration and Differential Equations 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!