I have a simple question that I wasn't able to find an answer to. I have a function f(x)
where x
is some vector, for example:
function f=f(x)
f=x.^4;
end
Then I want to integrate with bounds as vectors:
x=1:0.1:10;
x_0=2*ones(size(x));
g=integral(@f,x_0,x);
and I want to get g
as a vector g(i)=integral(@f,x_0(i),x(i))
. However, this will return an error that the bounds have to be scalars.
Obviously I can use a loop:
x=1:0.1:10;
x_0=2*ones(size(x));
for i=1:length(x)
g(i)=integral(@f,x_0(i),x(i));
end
but that can be very inefficient if I have big vectors that are repeatedly integrated.
Is there a simple efficient way to do this vectorized without a loop?
f
is just an example. Afor
loop is the way to do this. As the documentation indicates,integral
only handles scalar bounds. This makes sense as the integration might be quite different for different bounds, which would potentially diminish any benefits from parallelization.for
loops aren't terribly inefficient in current versions of Matlab. However, you should be sure to pre-allocate your outputg
. And if the lower boundx_0
is constant, then you don't need to turn it into a vector. $\endgroup$arrayfun
is other than afor
loop in disguise? ;-) And, as you indicate, it's often less efficient for applications like this. If you want faster, you'll need to implement your own quadrature routine, or solve the integral symbolically (or come up with a suitable approximation) and vectorize the evaluation of the result. $\endgroup$