Is there a manner to optimize (vectorize) this loop?
fval = 0
for i = 1:N
for j = i+1:N
z = y(i) - y(j) ;
fval = fval + z*z ;
end
end
fval = 2*fval
It is computing \sum_{i=1}^{N} \sum_{j=1}^{N} (x(i) - x(j))^2.
Thanks,
Chris
One way is with meshgrid and sum:
X = meshgrid(x);
f = sum(sum((X - X.').^2));
Just a note, optimize and vectorize are not the same thing. See the many recent posts on here where For loops crushed all comers in speed. Any given vectorization may or may not be faster than a well written For loop.
> > fval = 0
> > for i = 1:N
> > for j = i+1:N
> > z = y(i) - y(j) ;
> > fval = fval + z*z ;
> > end
> > end
> > fval = 2*fval
> >
> > It is computing \sum_{i=1}^{N} \sum_{j=1}^{N} (x(i) - x(j))^2.
> >
> > Thanks,
> >
> > Chris
>
> One way is with meshgrid and sum:
>
> X = meshgrid(x);
> f = sum(sum((X - X.').^2));
You could vectorize this with bsxfun, but I think your For loop is going to beat it in speed. The above solution (with meshgrid) is certainly slower and uses more memory.
suppose y is column vector (if not, columnize it)
this line will do the job:
f = 2*((n+1)*sum(y.^2)-2*cumsum(y')*y);
This seems to work, but could somebody please explain what happend?
doc cumsum
doc sum
What else do you need to know?