Need help solivng euler method code
Información
La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.
Mostrar comentarios más antiguos
We had to create a matlab function based off of the euler method from calculus. I am having an issue getting my code to work. The code just outputs an array of 1001 zeros instead of the calculated values. Can I get help fixing my euler method code?
Inputs for function >>>>>>>>> t0=0, tf=f, h=0.005, y0=10
The differential equation is >>>>> dy/dt = -0.1 * y
function [y] = euler1(t0,tf,dt,y0)
%euler: utilizes the euler method to solve a differential equation
% Input:
% h ........ step size
% xi ....... starting position
% xf ....... ending position
% y0 ...... Intitial y value
% Output:
% y ........ function value
x = (t0:dt:tf);
y = zeros(size(x));
n = numel(y0);
for i=1:n-1
f = -0.1 *y;
y(i+1) = y(i) + dt * f;
end
end
Respuestas (1)
James Tursa
el 23 de Abr. de 2020
Editada: James Tursa
el 23 de Abr. de 2020
This
n = numel(y0);
needs to be this instead
n = numel(x); % number of independent variable values
Then you need to initialize your output array with the initial value. So add this line just before the for-loop:
y(1) = y0; % initial y value goes in the 1st spot
Then inside your for-loop, this line
f = -0.1 *y; % this sets f to be -0.1 times the ENTIRE y array, not what we want
needs to be indexed, like this
f = -0.1 *y(i); % this sets f to be -0.1 times the current value of y(i) only
La pregunta está cerrada.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!