My Mathlab code is giving me a wrong answer, and I don't know why.

14 views (last 30 days)
I'm trying to write a script to use Euler's method to solve ODE's. In line 10, I'm running into issues. On the second iteration, my code is telling me that 2 + 1 * 2 = 3.
I should clarify that I'm just using the problem off of the Euler's Method wikipedia page in which:
y' = y
y(0) = 1
Here's my code:
iterations = 4;
initial = [0,1];
step_size = 1;
f = @(x) initial(2);
while iterations > 0
initial(2) = initial(2) + step_size * f(initial(1));
initial(1) = initial(1) + step_size;
iterations = iterations - 1;
end
%Report Answer
initial(2)

Accepted Answer

OCDER
OCDER on 6 Nov 2017
Edited: OCDER on 6 Nov 2017
Move the function handle f inside the while loop. The moment a function handle is created, it uses all constants at the CURRENT state the function handle was generated. The variable initial, when the function handle was generated, is [0 1] and is never updated in the loop. This fixes the issue:
iterations = 4;
initial = [0,1];
step_size = 1;
while iterations > 0
f = @(x) initial(2);
initial(2) = initial(2) + step_size * f(initial(1)); %Same as: initial(2) + step_size*initial(2)
initial(1) = initial(1) + step_size;
iterations = iterations - 1;
end

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!