MATLAB: Error using command integral


i have to valute this function
and plot the graphics for , i wrote:
and here i get:
'Error using integral (line 85)
A and B must be floating-point scalars.'
so i can't plot(u,q).. what can i do??
Thanks for the support and soryr for my bad english.

Best Answer

  • Simplest is to just use cumtrapz. All you want is a plot anyway.
    u = linspace(0,4,1000);
    fun = @(x)exp(-x.^2);
    If all you want is the plot, then using a little bb-gun (cumtrapz) can be better than wielding a big gun like integral.
    If you wanted to use integral, then you need to recognize that integral is not designed to solve a cumulative integral, so for an entire list of upper limits. You can't give it a vector of limits, and want it to work directly.
    Simplest then could be to use a loop.
    u = linspace(0,4,1000);
    fun = @(x)exp(-x.^2);
    uint = zeros(size(u));
    for i = 2:numel(u)
    uint(i) = integral(fun,u(i-1),u(i));
    uint = cumsum(uint);
    As you can see, I only integrate each segment, then I formed the cumulative sum. This will be more efficient than integrating from 0 to u(i), each pass through the loop, since there is no need to re-integrate the early parts each time.
    Finally, if you ABSOLUTELY, POSITIVELY, DESPERATELY need to do the integral in a vectorized form, you could do it, but why? Writing "elegantly" vectorized code will often result in less readable, code, that is hard to debug. Unless there is a reason for efficiency, the vectorized form may be of little real value. But, CAN you? Sigh. Yes.
    u = linspace(0,4,1000);
    fun = @(x)exp(-x.^2);
    intfun = @(upplim) integral(fun,0,upplim);
    uint = arrayfun(intfun,u);
    The simplest code (the first) is the most efficient code. It is readable. Not always quite as accurate, but by use of a sufficiently fine grid spacing, it will be quite adequate. And the spacing used here? 1000 steps, from 0-4? Trapzezoidal rule is entirely adequate for such a fine spacing.