user123456
user123456

Reputation: 374

Using a function that has another function as parameter:

I want to integrate x^2 from 2 to 4 with the trapezoidal integration method. For this, I defined a function trap that takes 4 arguments:

function y = trap( fn, a, b, h )
    n = (b-a)/h;
    x = a + [1:n-1]*h;
    y = h/2*(feval(fn, a) + feval(fn, b) + 2*sum(feval(fn,x)));

and a function f

function y= f(x)
    y=x^2
end

Now, by executing trap(f,2,4,0.1), I get the following error:

Not enough input arguments.

Error in f (line 2)
    y=x^2

What is the origin of that error?

Upvotes: 1

Views: 55

Answers (1)

anon
anon

Reputation:

You have to call trap using the function handle @f, not f.

trap(@f,2,4,0.1)

function y = trap( fn, a, b, h )
  n = (b-a)/h;
  x = a + [1:n-1]*h;
  y = h/2*(fn(a) + fn(b) + 2*sum(fn(x)));
end

function y= f(x)
  y = x.^2;
end

which gives, as expected,

ans =
    18.67

Also you needed element-wise multiplication in f(x) to compute y = x.^2.

And feval is not necessary. You can directly call fn(a) to evaluate the function.

Upvotes: 2

Related Questions