Recursive Method returning answers backwards

10 ビュー (過去 30 日間)
Chas
Chas 2023 年 5 月 2 日
コメント済み: Torsten 2023 年 5 月 7 日
Consider my code for Euler's Method below. If you run the code, you will see the correct values be stored in the matrix "vals", but after the return statement, the "vals" that is returned is from the first iteration. Why does MATLAB do this?
f = @(x,y)(x^2*(2+y));
ans = euler(1, 0.1, f, 0.0, 1.0, [])
function vals = euler(y,h,f,start,finish,vals)
if (finish - h < start)
y;
return
else
y = y + h*f(start,y)
start = start + h
vals = [vals,y]
euler(y,h,f,start,finish, vals)
end
end
  1 件のコメント
John D'Errico
John D'Errico 2023 年 5 月 2 日
編集済み: John D'Errico 2023 年 5 月 2 日
MATLAB does what you tell it to do. It is not DOING anything to you. Just your code, code written in error. Why you are usign recursion, I don't know, since Euler is simple to write with a loop. Read the answer from James.

サインインしてコメントする。

採用された回答

James Tursa
James Tursa 2023 年 5 月 2 日
編集済み: James Tursa 2023 年 5 月 2 日
This is a very convoluted way to program the Euler method. There is no need for recursion here, just use simple loops instead.
Regarding why you aren't getting the results you expected, it has to do with how you update vals. Your very first call to Euler is this:
ans = euler(1, 0.1, f, 0.0, 1.0, [])
which returns the vals from the very first call via this line:
vals = [vals,y]
but then in all your subsequent calls to euler( ) you throw away the returned vals:
% you don't save the returned vals, so this line essentially accomplishes nothing
euler(y,h,f,start,finish, vals)
Maybe changing this euler( ) call to this might get you what you expected:
vals = euler(y,h,f,start,finish, vals)
But, seriously, this code is convoluted and hard to follow because of the recursion. It would be best to rewrite it as a simple loop.
  2 件のコメント
Chas
Chas 2023 年 5 月 7 日
I already had done it with a loop and was curious to figure out how recursion worked in MATLAB. What is a fix to this code? I can't think of one based on your explination.
Torsten
Torsten 2023 年 5 月 7 日
Didn't you read to use
vals = euler(y,h,f,start,finish, vals)
instead of
euler(y,h,f,start,finish, vals)
in your code ?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeNumerical Integration and Differentiation についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by