简体   繁体   中英

matlab: not enough input arguments error

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

当您将f传递给euler您需要将其作为句柄传递,即在它前面加上@

e = euler(@f, trange(1), y0_value, h, trange(end));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM