dpb
Posts:
8,512
Registered:
6/7/07


Re: vectorization loops
Posted:
Feb 5, 2013 1:22 PM


On 2/5/2013 11:17 AM, Christian wrote: > Hello, > does there exist something like an approach for vectorization loops (2, > 3 or 4 nested loops)? ...
Completely general, no, most have to be analyzed based on the characteristics of what is in the loop(s) and the loop structure itself...
> Example for discussion: > > n=3; > a=rand(n,n); > for i=1:n > for j=1:n > b = b + a(i,j)*a(j,i); % command > end > end > b > > Okay, the innermost loop is absolutely no problem, but what's with the > outer one.
Consider what the above operations do...for this particular case,
s=x'.*x; s=sum(s(:);
which can be written in several other ways...
s=sum(sum(x'.*x)); s=sum(dot(x'.*x));
>> x=rand(3); >> s=0;for i=1:3,for j=1:3,s=s+x(i,j)*x(j,i);end,end,s s = 3.1787 >> s=x'.*x; s=sum(s(:)) s = 3.1787 >> s=sum(sum(x'.*x)) s = 3.1787 >> s=sum(dot(x',x)) s = 3.1787 >>
So, the key is in recognizing the algebraic expression and often on how it relates to linear algebra, etc., ...


