1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| format long;
h = 1/20;
xf = 2;
x = 0 : h : xf;
Func = @(x, y)(y - ((2 * x) / y));
y_E = zeros(1, length(x)); y_E(1) = 1;
for i = 1:(length(x)-1) y_E(i + 1) = y_E(i) + Func(x(i), y_E(i)) * h; end
y_IE = zeros(1, length(x)); y_IE(1) = 1;
for i = 1:(length(x) - 1) p = y_IE(i) + h * Func(x(i), y_IE(i)); c = y_IE(i) + h * Func(x(i + 1), p); y_IE(i + 1) = (1/2) * (p + c); end
y_RK = zeros(1, length(x)); y_RK(1) = 1;
for i=1:(length(x) - 1) k1 = Func(x(i), y_RK(i)); k2 = Func(x(i) + 0.5 * h, y_RK(i) + 0.5 * h * k1); k3 = Func((x(i) + 0.5 * h), (y_RK(i) + 0.5 * h * k2)); k4 = Func((x(i) + h), (y_RK(i) + k3 * h)); y_RK(i + 1) = y_RK(i) + (1 / 6) * (k1 + 2 * k2 + 2 * k3 + k4) * h; end
x0 = 0; y0 = 1; yspan = [x0 xf]; [x_ode45, y_ode45] = ode45(Func,yspan,y0);
subplot(221) plot(x_ode45, y_ode45, '-'); xlabel('x'); ylabel('y'); legend('Exact');
subplot(222) plot(x, y_E, '-'); xlabel('x'); ylabel('y'); legend('Euler');
subplot(223) plot(x, y_IE, '-'); xlabel('x'); ylabel('y'); legend('Improve Euler');
subplot(224) plot(x, y_RK, '-'); xlabel('x'); ylabel('y'); legend('Rung Kutta');
res = [round(transpose(x), 8), round(transpose(y_E), 8), round(transpose(y_IE), 8), round(transpose(y_RK), 8), round(y_ode45, 8)]; table = array2table(res, 'VariableNames', {'x','Euler','Improve Euler', 'Rung Kutta', 'Exact'}); table;
|