Euler method for ODE

3 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by