1

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));
Matt
  • 29
  • 1
  • 5

1 Answers1

1

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
David
  • 8,449
  • 1
  • 22
  • 32
  • By instruction, I must use a separate m.file for the equation. The user can't just enter an equation into the second function. What you showed does seem much simpler, however. I want to be able to use the second function by: trapez('f',a,b,n) – Matt Apr 15 '14 at 02:12
  • I have edited my original question to show how I'm trying to execute the functions in the command window – Matt Apr 15 '14 at 02:23
  • In the `trapez` function you have a syntax error. `sum(feval,f,x)` should be `sum(feval(f,x))`. In fact you can just do `f(x)`, you don't need to use `feval`. You do need to be careful though as `exp(x^2)` doesn't work for vector input. – David Apr 15 '14 at 02:30
  • I edited my answer -- check the last two functions, `myf` and `trapez`. – David Apr 15 '14 at 02:34