Anna
Anna

Reputation:

How can I speed up my loop?

I have the following code that takes ages to run. How could I speed it up?

for n = 1:10000;
 syms L_0;
 m(n)=log10(n);
 L_0=max(vpasolve(Equilibrium(L_0,n)==0,L_0));
 L_1(n)=L_0;
end

for i=1:10000;
  q_1(i)=q(L_1(i));
end

plot(m,q_1)

Upvotes: 0

Views: 124

Answers (2)

Morc
Morc

Reputation: 381

Without knowing too much about the function you are numerically solving, I would start with preallocating the memory for the arrays. For each iteration you are resizing the memory footprint which requires the equivalent of a malloc and copying the array to new location for the incremented size. Sometimes this can be optimized out if there is room in memory for the array to grow but not guaranteed and not within programmer control.

L_1 = zeros(1,100000);
m = zeros(1,100000);
q_1 = zeros(1,100000);

I found that whenever I have loops and large vectors it always pays to preallocate first. The next step would be looking into the numerical solver. Is this a system you could solve without invoking syms? Is it a system of PDEs or linear equations? Could you utilize any builtin Matlab matrix functions? Those are matlab's bread and butter and usually pretty speedy!

And always worth running profile viewer on it and find the bottleneck. Here it is very likely the numerical solver but never hurts to confirm.

Upvotes: 1

HEITZ
HEITZ

Reputation: 136

Agree with @Morc that if you can redefine the computations to use matrix multiplication you'll see impressive performance gains. But not knowing those functions, I don't know if that's possible. Other options:

If you have it, enable the parallel toolbox and use parfor. If your loop can be defined using parfor (not all are), this will help.

Finally, you can rewrite the most time consuming parts (use the profiler to figure that out) in C and compile it to a MEX function. MEX is a C-compiled function you can call from matlab.

Upvotes: 0

Related Questions