Question

Is there any way in Matlab, to shorten this function or is there any built-in function I can use instead of this? The following function works for me, but I want to exclude it from my script.

function p = nintegrate(x, fx)
    acc = 0;
    for i = 1:length(x)-1
            p(i) = acc;
            delta_x = x(i+1) - x(i);
            acc = acc + delta_x * fx(i);
    end
end
Was it helpful?

Solution

Have a look at cumtrapz, which does something similar. It used trapezoidal integration, which is a slightly better way of doing numerical integration. Usage in your case should be (untested):

acc = cumtrapz(x, fx);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top