optimise nested for-loop

1 visualizzazione (ultimi 30 giorni)
Muna Tageldin
Muna Tageldin il 28 Set 2020
I have this function (test) which uses nested-for loops, usually the function takes 75 seconds (interested in <4 seconds).
function l1=test(a,z)
f=zeros(size(z));
[ep,u,lam]=ndgrid(1e-3:1e-2:0.99,1e-3:1e-2:0.99,1e-3:1e-2:0.99);
l1=zeros(size(ep));
for i=1:size(ep,1)
for p=1:size(ep,2)
for o=1:size(ep,3)
l1(i,p,o)=ep(i,p,o)*lam(i,p,o)+sum(a*u(i,p,o)*exp(-z));
end
end
end
end
z is an array of data (size >4000)
I tried to use bsxfun and vectorize the code by appending zeros to z and reshaping ep,lam and u, but I am faced with MATLAB limitations (required memory 70 GB of RAM). To vectorize it, I appneded zeros to array z then with multiplication I got the following:
l1=(ep.*lam)+sum(a*u.'.*z);
the multiplication of a*u.'.*z results in (1e6,1e6) matrix. How can I solve this problem?
I tried also using tall array but no sucess. Is there a method I can use that can speedup this function
I also looked up the below link for solutions to memory out of bound.

Risposte (1)

sushanth govinahallisathyanarayana
Is a a constant? You can pre-calculate ep(i,p,o)*lam(i,p,o) outside the loop as
ep(i,p,o).*lam(i,p,o). Then you only have a loop over z to work with. What is the dimensions of z? ep, u and lam are 99x99x99 cubes. You can replicate z in one of the directions and make it simpler to compute.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by