Reputation: 5376
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
Upvotes: 2
Views: 901
Reputation: 18488
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);
Upvotes: 4