Vectorize double loops with constraints on the indexes

1 visualización (últimos 30 días)
AC
AC el 4 de Jul. de 2012
Hi,
I would like to speed up part of my code. While I kind of know how to vectorize loops in general, I'm stuck with a problem here that I'm not sure how to handle.
I have a double loop and the set of indexes for the second one depends on the first one.
k=2; d=40; lambda=1;
z=rand(d+2,1);
B=zeros(k,d); A=zeros(k,d); C=zeros(k,d);
for l=0:d-1
for r=max(k-(d-l),0):min(l,k-1)
A(r+1,l+1)=lambda/(lambda+1)*z(k-r);
B(r+1,l+1)=lambda/((1+l)*lambda+r+1)*sum(z(k-r+2:k-r+l+1));
C(r+1,l+1)=z(k-r+l+2);
end
end
In theory, I could vectorize it for l in 0:d-1, r in 0:k-1 and then filter out unwanted elements. However, some computations just won't work in this case and I'll get error messages (empty arrays, index out of bounds,...).
Does anyone have an idea to speed this up? (k and d may become much larger than in this example so speed is an issue).
Thanks a whole lot in advance!
AC
  5 comentarios
John Petersen
John Petersen el 6 de Jul. de 2012
Write it in C and use it as a mex function. Otherwise, if you can write it in pseudo code without loops, post that and someone will likely be able to help you code it in matlab.
AC
AC el 9 de Jul. de 2012
Wow! Thanks so much to all of you for the answers! Let me test your proposals, but it looks very very good! And there I was thinking I was gonna have to drop it. So cool, you rock! Thank you!

Iniciar sesión para comentar.

Respuestas (3)

Jan
Jan el 7 de Jul. de 2012
Editada: Jan el 8 de Jul. de 2012
Calculating the cumulative sum repeatedly consumes a lot of time. Using cumsum this can be made more efficiently with tiny differences by round-off in the magnitude of EPS for RAND data. Please check if these rounding differences can be neglected for your data.
k = 100;
d = 1e4;
lambda = 1;
z = rand(d+2,1);
B = zeros(k,d);
A = zeros(k,d);
C = zeros(k,d);
zc = cumsum(z);
for s = 0:d-1
for r = max(k-(d-s),0):min(s,k-1)
A(r+1,s+1) = lambda/(lambda+1)*z(k-r);
C(r+1,s+1) = z(k-r+s+2);
ci = k - r + 2;
cf = k - r + s + 1;
if ci <= cf
B(r+1, s+1) = lambda / ((s+1) * lambda + r + 1) * (zs(cf) - zs(ci-1));
end
end
end
I've renamed "l" (lowercase L) to "s" to avoid the confusion with "1" (one).
This reduces the processing time for k=100, d=1e4 from 30.42 sec to 0.12 sec. Fine!
After the sum is not the bottleneck anymore, other details get important: Computing r+1, s+1 and lambda/(lambda+1) repeatedly wastes time. Create temporary variables in the outermost possible loop (is this still English?) to save further computing time:
t1 = lambda / (lambda + 1);
for s = 0:d-1
s1 = s + 1;
s1lambda = s1 * lambda;
for r = max(k-(d-s),0):min(s,k-1)
r1 = r + 1;
A(r1, s1) = t1 * z(k-r);
if s1 >= 2
B(r1, s1) = lambda / (s1lambda + r1) * (zs(k - r + s1) - zs(k - r + 1));
end
C(r1, s1) = z(k-r+s+2);
end
end
0.09947 sec, more than 300 times faster.
Converting the original algorithm to C would suffer from the repeated summing also. So if you want to spend time in further optimization, start from the cleaned method.
Summary: Avoid repeated calculations of the same data.
[EDITED] A partially vectorized method to create C:
for s = 0:d-1
q = k + s + 2;
m1 = max(k - d + s, 0);
m2 = min(s, k-1);
C(m1+1:m2+1, s+1) = z(q - m1:-1:q - m2);
% Loop method for A and B
end
But this is 50% slower than the loop already, because creating the temporary vectors needs a lot of time. Therefore I think that the cleaned loop is remarkably faster than a partially or completely vectorized version.

Andrei Bobrov
Andrei Bobrov el 8 de Jul. de 2012
other variant
eg:
% input data
k = 10;
d = 40;
lambda = 1;
z = randi(12,d+2,1);
% solution
B = zeros(k,d);
A = zeros(k,d);
C = zeros(k,d);
t = logical(convmtx(true(1,d-k+1),k));
[ra,la] = ndgrid(1:k,1:d);
r = ra(t);
l = la(t);
zs = cumsum(z);
i1 = k - r + 1;
i2 = i1 + l;
idx = sub2ind([k,d],r,l);
A(idx)=lambda/(lambda+1)*z(i1);
B(idx)=lambda./(l*lambda+r).*(zs(i2) - zs(i1+1));
C(idx)=z(i2+1);
  1 comentario
Jan
Jan el 9 de Jul. de 2012
Editada: Jan el 9 de Jul. de 2012
+1: A nice vectorization. I get a runtime of 0.471 sec for k=100, d=1e4, while the leal loop takes 0.1 sec (Matlab 2009a/64, Win7). Therefore this is another useful example to compare loop and vectorization.

Iniciar sesión para comentar.


Mark Whirdy
Mark Whirdy el 7 de Jul. de 2012
Hi Anne-Claire
I can make some progress in the vectorization here (code below) but there are a few issues.
1) The r=max(k-(d-l),0):min(l,k-1) logic for the iteration of i results in all A,B,C elements being populated except for (2,1) and (1,40). I have emulated this in logical matrix as "vMask" below but it is a little hardcoded since I don't totally appreciate the algo's context so can't guarantee that it is robust in terms of other k,d,lambda values.
2) In your code in the very first iteration, it attempts to populate B(1,1) with
1/((1+0)*1+0+1)*sum(z(2-0+2:2-0+0+1));
but note that z(4:2) is an empty matrix [i.e. not the same as z(4:-1:2)] and sum(z(4:2))=0, somewhat spuriously. Is this the intended behaviour of the algorithm? I stopped short of writing a vectorized version of B & C since it seems a little unusual.
Best Rgs,
Mark
%%Vectorization Approach - first draft
B=zeros(k,d); A=zeros(k,d); C=zeros(k,d);
l = 0:d-1; L = l(ones(k,1),:); % repmat l -> L
r = 0:1; R = r(ones(d,1),:)'; % repmat r -> R
vMask = (R==max(k-(d-L),0) | R==min(L,k-1)); % Validation Mask
A(vMask) = lambda./(lambda+1).*z(k-R(vMask));
  1 comentario
Mark Whirdy
Mark Whirdy el 7 de Jul. de 2012
Actually, looking at the k = 100;d = 1e4 case I see its definitely not robust but can be pretty easily adapted by changing vMask.
Come back to me on point 2 tho.
Best Rgs, Mark

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by