I am currently working on Matlab code to solve a second-order differential equation. From there, I convert the equation into a system of two first-order differential equations. I am unsure how solve the system of equations with the initial values provided below using Euler's method first and then using 2nd order Runge-Kutta method.
In my code below, I tried transposing the initial values array y0, but I still am receiving the following error:
%%
Error using indexing
Invalid argument at position 2. Symbolic function expected 1 input arguments but received 2.
Error in matlab_sample0 (line 49)
y_num(:,i + 1) = y_num(:,i) + (h * f(t(i),
y_num(:,i)));
%%
clear;
clc;
clf;
syms f(t)
%y" = g(t) - 2y' - 2y
% input values
h = pi/50;
t0 = 0;
tfinal = 2*pi;
t = 0:h:tfinal;
n = round(tfinal/h);
% Euler's method
y0 = [1; 0];
y_num = zeros(2, n + 1);
y_num(:,1) = y0;
for i = 1:n
y_num(:,i + 1) = y_num(:,i) + (h * f(t(i), y_num(:,i)));
end
%exact solution
exact_sol = @(t,x) [x2; -2*x2-2*x1];
y_exact = zeros(1, n + 1);
for i = 1:(n + 1)
y_exact(i) = exact_sol(t(i));
end
%plot figure
figure;
plot(t, y_num, '-k', t, y_exact, '--r')
xlabel('t'); ylabel('y');
title("Euler's method Comparison between numerical and exact solutions");