Solve the system
\begin{align*}
y_1' \amp = t - 3y_2\\
y_2' \amp = 2y_1
\end{align*}
with initial condition \(y(0) = \begin{pmatrix}1 \\ 0\end{pmatrix}\text{,}\) on the interval \([0, 10]\) using the trapezoidal method with the step \(h=0.01\text{.}\) Plot the solution.
Answer.
f = @(t, y) [t-3*y(2); 2*y(1)];
h = 0.01;
t = 0:h:10;
y0 = [1; 0];
y = y0*ones(size(t));
for k = 1:numel(t)-1
pred = y(:, k) + h*f(t(k), y(:, k));
y(:, k+1) = y(:, k) + h/2*(f(t(k), y(:, k)) + f(t(k+1), pred));
end
plot(t, y)
The most visible difference is the notation
y(:, k) which takes the entire \(k\)th column of the matrix y. Its mathematical meaning is the approximation to \(\mathbf y(t_k)\text{.}\) The initial condition y0 is a column vector, which makes the computation y = y0*ones(size(t)); an outer product: it creates a matrix in which every column is equal to y0. This is convenient because we need the first column to be equal, and the other columns will be rewritten anyway.
