Search code examples
matlabfunctionfunction-handle

Calling separate functions in Matlab


I'm trying to call a a function that allows the user to input an equation of their choosing, and then use a separate function to approximate it using the trapezoidal rule in numerical analysis.

Here's my code for the user input equation:

    function f = myf(x)
    y=@(x) input('Input Equation:  ');
    f=y(x);
    end

And here's the code for applying the trapezoidal rule:

    function T=trapez(f,a,b,n)
    h=(b-a)/n;
    x=[a+h:h:b-h];
    T=h/2*(feval(f,a)+feval(f,b)+2*sum(feval,f,x));
    fprintf('The approximation by trapezoida rule is: %f with step h: %f\n',T,h);
    end

My issue is trying to use the equation determined by the first function as an input in the second.

    >> f=myfun
    Input Equation: exp(x^2)

    f = 

    @(x)exp(x^2)


    f = 

    @(x)exp(x^2)

    >> trapez(f,0,1,15)
    Error using feval
    Not enough input arguments.

    Error in trapez (line 4)
    T=h/2*(feval(f,a)+feval(f,b)+2*sum(feval,f,x));

Solution

  • Here is the function to input the function,

    function f=myf
    y=input('Input equation: ','s');
    eval([ 'f=@(x)' y ';'])
    

    and use f=myf from another function.

    Also your trapez unction needs some modification:

    function T=trapez(f,a,b,n)
        h=(b-a)/n;
        x=[a+h:h:b-h];
        T=h/2*(f(a)+f(b)+2*sum(arrayfun(f,x)));
        fprintf('The approximation by trapezoida rule is: %f with step h: %f\n',T,h);
        end
    

    Depending on how the function is to be input, myf could be different. This should work if you give the input as, e.g.: x^2 (so just the function, not extra syntax)

    y=input('Input equation: ','s')
    eval([ 'f=@(x)' y])
    

    And a sample input/output:

    Input equation: x^2
    y =
    x^2
    f = 
        @(x)x^2
    

    and then you can do f(2) to find 2^2.

    Alternatively, if you want to input the function with its argument, e.g.: @(y) y^2

    y=input('Input equation: ','s')
    eval(['f=' y])
    

    and sample output:

    >> y=input('Input equation: ','s')
        eval(['f=' y])
    Input equation: @(t) t^2
    y =
    @(t) t^2
    f = 
        @(t)t^2
    >> f(2)
    ans =
         4