1

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?

1
  • Any reason to avoid trapz()? For example, xstep = 0.1; then X = 2:xstep:4; then Area = trapz(X,X.^2) works great. Decrease xstep size for Area to converge (with required precision). Commented Feb 13, 2020 at 18:23

1 Answer 1

2

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.

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.