MATLAB: How to vectorize the following the summation

summationvectorvectorization

This is the code that I have. It's taking up way too much time so I was wondering if it is possible to 'vectorize' it, to save time. Here's the code:
Sigma=zeros(n,n);
G=zeros(n,n);
for i=1:m
Sigma=(y(i)-x(i,:)*bhat).^2*(x(i,:)).'*x(i,:)+Sigma;
G=*(x(i,:)).'*x(i,:)+G;
end
Where x is a mXn matrix, y is a mX1 and bhat is a nX1. I have already vectorized G but I can't get Sigma to work. My best try so far is the following.
Sigma=x.'*(((y-x*bhat).')*(y-x*bhat))*x;
G=x.'x;
I already realize why it is wrong, but I can't fix it. Thanks for the help in advance.

Best Answer

Hi Cache,
To obtain G, the sum over the row index i of matrix x leads to the product
G = x.'*x
as you determined.
Sigma involves the very same sum over the row index, only with an extra factor (y(i)-x(i,:)*bhat).^2. The index i is the row index for the quantity y-x*bhat, which is a column vector. This suggests the following:
A = (y-x*bhat).^2;
Sigma = x.'*diag(A)*x
Related Question