Recursive Method returning answers backwards
Show older comments
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 Comment
John D'Errico
on 2 May 2023
Edited: John D'Errico
on 2 May 2023
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.
Accepted Answer
More Answers (0)
Categories
Find more on Numerical Integration and Differentiation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!