- #1
Gengar
- 13
- 0
I'm a newbie to all things programming, and have to write a program implementing the Euler method to approximate an ODE.
Anyways, the program works but when I use the function I wrote I get an extra matrix of zeroes above the desired output, which I don't understand as I have suppressed the output of the zero matrix with a semi-colon - the matrix is Eulerpoints. Here's the source code:
function [Eulerpoints] = Eulermethod(x0,y0,xn,steps)
%EULERMETHOD - this function will approximate y by the Euler method.
% EULERMETHOD(x0,y0,xn,steps) will return a list of points that
% approximate y in the interval [x0,xn] given our initial co-ordinate
% (x0,y0) and the number of steps.
Eulerpoints=zeros(steps+1,2);
start = 2;
finish = steps+1;
h=(xn-x0)/steps;
Eulerpoints(1,1) = x0, Eulerpoints(1,2) = y0;
fprintf(' n xn Yn\n 0 %2g %2g\n',x0,y0)
for I= start:finish
Eulerpoints(I,1) = x0 +h*(I-1);
Eulerpoints(I,2) = Eulerpoints(I-1,2) + h*(-2*Eulerpoints(I-1,2) - 0.25*Eulerpoints(I-1,1)*Eulerpoints(I-1,1) + 0.125); %% This line contains the ODE, which can be adjusted for a different equation.
fprintf('%3g %4g %6g\n',I-1,Eulerpoints(I,1),Eulerpoints(I,2))
end
%
end
Anyways, the program works but when I use the function I wrote I get an extra matrix of zeroes above the desired output, which I don't understand as I have suppressed the output of the zero matrix with a semi-colon - the matrix is Eulerpoints. Here's the source code:
function [Eulerpoints] = Eulermethod(x0,y0,xn,steps)
%EULERMETHOD - this function will approximate y by the Euler method.
% EULERMETHOD(x0,y0,xn,steps) will return a list of points that
% approximate y in the interval [x0,xn] given our initial co-ordinate
% (x0,y0) and the number of steps.
Eulerpoints=zeros(steps+1,2);
start = 2;
finish = steps+1;
h=(xn-x0)/steps;
Eulerpoints(1,1) = x0, Eulerpoints(1,2) = y0;
fprintf(' n xn Yn\n 0 %2g %2g\n',x0,y0)
for I= start:finish
Eulerpoints(I,1) = x0 +h*(I-1);
Eulerpoints(I,2) = Eulerpoints(I-1,2) + h*(-2*Eulerpoints(I-1,2) - 0.25*Eulerpoints(I-1,1)*Eulerpoints(I-1,1) + 0.125); %% This line contains the ODE, which can be adjusted for a different equation.
fprintf('%3g %4g %6g\n',I-1,Eulerpoints(I,1),Eulerpoints(I,2))
end
%
end