Need help solivng euler method code
信息
此问题已关闭。 请重新打开它进行编辑或回答。
显示 更早的评论
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
0 个评论
回答(1 个)
James Tursa
2020-4-23
编辑:James Tursa
2020-4-23
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
0 个评论
此问题已关闭。
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!