Euler method for ODE

조회 수: 2 (최근 30일)
PJS KUMAR
PJS KUMAR 2018년 9월 21일
답변: James Tursa 2018년 9월 21일
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

채택된 답변

James Tursa
James Tursa 2018년 9월 21일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by