evaluating integrals containing unknown functions using trapezoidal rule in matlab

287 Views Asked by At

How do I get a symbolic expression for the integration of the following function which contains an unknown function using trapezoidal rule?

$f(x) = \lambda(x) + x^2$

Integrate $\int^{b}_{a}f(x) $ using trapezoidal rule with a time step of $\Delta x_k = 0.1s$ from $t = 0s $ to $t =0.3s$

For example, desired output from Matlab for following function

$\int^{0.3}_{0} \lambda(x) + x^2$

will be approximated (using the trapezoidal rule) as

$\approx [{\frac{0.1}{2} (\;\;f(0.1)+f(0.0)\;)\;+\;\frac{0.1}{2} (\;\;f(0.2)+f(0.1)\;)\;+\frac{0.1}{2} (\;\;f(0.3)+f(0.2)\;)}] $

Your code in Matlab should be able to evaluate this expression from trapezoidal rule and give the final answer which includes the symbolic expression for the unknown $\lambda(0.0),\;\lambda(0.1),\;\lambda(0.2),\;\lambda(0.3) $

This is how your Matlab code evaluate $f(0.1)$ as an example $$ f(0.1) = \lambda(0.1) +\,(0.1)^2=\lambda(0.1)+0.01$$

1

There are 1 best solutions below

7
On

I come up with the code using Octave, please try if the code works for you as well.

Firstly, create the symbolic function $\lambda(x)$.

syms lambda(x)

After that, define the anonymous function $f(x)$

f = @(x) lambda(x) + x ^ 2

Next, define the trapezoidal rule as an anonymous function. (I use the formula for uniform grid.)

trapezoidal = @(f, a, b, delta_x) ...
               delta_x / 2 * ...
              (f(a) + ...
               sum(arrayfun(f, ...
                            (a + delta_x) : ...
                            (delta_x) : ...
                            (b - delta_x))) * 2 + ...
               f(b))

Finally, to get the result

trapezoidal(f, sym('0'), sym('3 / 10'), sym('1 / 10'))

Hope it helps.