I have the following code to solve some ordinary differential equation(ODE). In order to relieve myself of the burden of typing a long expression in each iteration of the for loop I decided to define an anonymous function. When I defined the anonymous function before initializing x vector it turned out an error since it used the elements of the vector x in calculations. The anonymous function is as follows:
fnc = @(i) (-100 * (x(i) - cos(h * t(i))) - sin(h * t(i)));
In order to resolve the problem I initialized all elements of x to be zeros beforehand to avoid it complaining as follows:
Undefined function 'x' for input
arguments of type 'double'.
However, it turned out to mess up with solution depending on where I put the anonymous function. What may be the reason for this behaviour? My code can be found below, you can see the commented out regions to see where I tried to implement the anonymous function.
close all;
clear all;
clc;
t_s = 0; % Starting time
t_f = 1; % Finishing time
h = 0.2; % Time step
t = t_s:h:t_f;
N = (t_f - t_s) / h; % Number of time steps (excluding initial points)
% x = zeros(1, N + 1);
fnc = @(i) (-100 * (x(i) - cos(h * t(i))) - sin(h * t(i)));
x(1) = 1; % Initial condition given in the problem
x(2) = x(1) + h * fnc(1);
for in = 3:N+1
% fnc = @(i) (-100 * (x(i) - cos(h * t(i))) - sin(h * t(i)));
x(in) = x(in - 1) + (3 / 2) * h * fnc(in - 1) + (-1 / 2) * h * fnc(in - 2);
end