Euler method for ODE

2 views (last 30 days)
PJS KUMAR
PJS KUMAR on 21 Sep 2018
Answered: James Tursa on 21 Sep 2018
I wrote the following code for Euler method
function sol=Euler2(fn,a,b,y0,n)
h=(b-a)/n;
x=a:h:b;
y(1)=y0;
for k=1:n
y(k+1)=y(k)+h*feval(fn,x(k),y(k));
end
sol=[x',y'];
Suggest me to obtain 'y' vector without 'for' loop, i.e., vectorising statement which can replace the 'for' loop

Accepted Answer

James Tursa
James Tursa on 21 Sep 2018
In general, you can't "vectorize" this process as you suggest. Since the calculation for y(k+1) depends on y(k), the calculation must be done in a loop as you are currently doing. An exception would be in cases where the fn function was of a form where the entire result could be obtained analytically (e.g., fn was a constant). But for your case, where fn is some arbitrary function being passed in, you cannot do that and as a result you will need the loop.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!