1

I am new to Matlab and trying to find a solution to the error of my code:

Not enough input arguments.
Error in F9>f (line 42)
y = (2 - 2*t*x) / (x^2 + 1) ;
Error in F9 (line 18)
e = euler(f, trange(1), y0_value, h, trange(end));

function [] = F9()
% Euler's Method to solve given functions
% Set initial values
hi = [1/2, 1/4];
trange = [0, 2];
y0_value = 1;
% Set functions' and exact functions' handles
% Calculate and show results
% Loop for functions
for i = 1:2
    fprintf('###########\n');
    fprintf('Function #%d\n', i)
    fprintf('###########\n');
    exact_value = f_exact(trange(end));
    % Loop for h
    for h = hi
        % Euler calculations
        e = euler(f, trange(1), y0_value, h, trange(end));
        fprintf('\nh: %f\n', h);
        fprintf('\nEuler: %f \n', e(end));
        fprintf('Error: %f\n\n', abs((e(end)-exact_value)/exact_value));
    end
    fprintf('Exact: %f\n\n', exact_value);
end
end
% Euler's Method
function y = euler(f, t0, y0, h, tn)
n = (tn-t0)/h;
% Initialize t, y
[t, y] = deal(zeros(n, 1));
% Set t0, y0
t(1) = t0;
y(1) = y0;
for i = 1:n
    t(i+1) = t(i) + h;
    y(i+1) = y(i) + h/2 * (f(t(i), y(i))+ f(t(i+1) , y(i) + h * f(t(i), y(i))));
end
end
% Functions to solve

function y = f(t, x)
y = (2 - 2*t*x) / (x^2 + 1) ;
end
function y = f_exact(x)
y = (2*x + 1) / (x^2 + 1);
end
0

1 Answer 1

1

When you pass f to euler you need to pass it as a handle, i.e. precede it with a @:

e = euler(@f, trange(1), y0_value, h, trange(end));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.