# y'=1-(y/x), y(2)=-1, change in x =0.5. Im supposed to use Euler method to solve this differential equation but I'm not getting the answer I want. I have the code but I'm not sure if I'm doing it right.

5 views (last 30 days)
Rose Ahmad on 23 Oct 2020
Commented: Rose Ahmad on 24 Oct 2020
This is my input and output. Im not sure why im not getting f. Am I like using the wrong code. I also think my y outputs are wrong. Please help!
Equation y'=1-(y/x), y(2)=-1, change in x =0.5.
h = 0.5 % step size
x = 2:h:1.5; % the range of x
y = zeros(size(x));
y(2) = -1; % the initial y value
n = numel(y);
for i=2:n-2
f = 1-(y(i)/x(i)) % the equation
y(i+1) = y(i) + (h * f);
end
y
h =
0.5000
y =
0 -1

KSSV on 23 Oct 2020
Your x value is not correct: You need to check this line:
x = 2:h:1.5; % the range of x
In the above you need to make changes.
h = 0.05 % step size
x = 1.5:h:2; % the range of x
y = zeros(size(x));
y(1) = -1; % the initial y value
n = numel(y);
for i=2:n-2
f = 1-(y(i)/x(i)) % the equation
y(i+1) = y(i) + (h * f);
end

KSSV on 23 Oct 2020
You have to check the loop index...I think the loop index for y should be (i-1).
h = 0.05 % step size
x = 1.5:h:2; % the range of x
y = zeros(size(x));
y(1) = -1; % the initial y value
n = numel(y);
for i=2:n-2
f = 1-(y(i-1)/x(i-1)) % the equation
y(i) = y(i-1) + (h * f);
end
If not, there is no necessity of loop.
Rose Ahmad on 24 Oct 2020
Thank you for your help! I tried changing things but it still didnt work. But I was able to find another code and was able to fgure it out.