Question

I asked a previous question about having an integral within a loop. I received an answer but it is unbearably slow. I was wondering if anyone could make it faster, I imagine removing loops and removing function definition from the loop.

l=3;
t=linspace(0,1,365);
fun3= @(v) integral(@(v)exp(.071*v),0,v,'ArrayValued',true);
for i=2:length(t)
  for j=i:length(t)
      xx=t(i);
      yy=t(j);
      fun  = @(x,y) exp(0.14*0.00607*fun3(yy)).*exp(-(x-y).^2/l).*exp(0.14*0.00607*fun3(xx));
      y(i,j)=integral2(fun,t(i-1),t(i),t(j-1),t(j));
  end
end
Was it helpful?

Solution

Yes, for loops are notoriously slow in Matlab. I usually use the function arrayfun to avoid using them.

Example:

[i,j] = meshgrid(1:length(t));
y = arrayfun(@(i,j)integral2(fun,t(i-1),t(i),t(j-1),t(j)),i,j)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top