Search code examples
matlabmat

Trapezodial Rule Matlab


I am completing an assignment for a class. We were to follow a flow chart to find the values for the trap rule code. I believe the problem is with my main code.

I am not sure if there is a problem with my function code or my main code, any help would be appreciated.

when I run the section, it display the function as the answer

The following is my mainscript code:

f = @(x)  (4*sin (x)) / (exp(2*x)) ;

trap_haskell(f , 0 , 3 , 7)

The rest is my trapezoidal rule code

function [f] = trap_haskell(f, a, b, n)


x = a ;
h = (b - a) / n ;
s = f (a) ;

for k=1:1:n-1 
    x = x + h ;
    s = s + 2 * f(x) ;
end

s = s + f(b) ;
I = (b - a) * s / (2 * n) ;

end

Solution

  • You're returning f as the output argument of trap_haskell which is the input function into trap_haskell itself. The variable I in your code actually stores the integral so it's simply a matter of changing the output variable of the function definition to return the integral instead:

    %//       ------ Change here
    %//       |
    %//       V
    function [I] = trap_haskell(f, a, b, n)