How do I vectorize the following the summation?

4 views (last 30 days)
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.

Accepted Answer

David Goodmanson
David Goodmanson on 27 Jun 2017
Edited: David Goodmanson on 27 Jun 2017
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
  3 Comments
Cache Ellsworth
Cache Ellsworth on 27 Jun 2017
Hi David, This is pretty great. Thanks. The only problem is that my data is too large to make A a square matrix. ( It exceeds maximum array size preference. It would be 830479x830479) Is there another way to add the extra factor without making a large square matrix?
David Goodmanson
David Goodmanson on 27 Jun 2017
Edited: David Goodmanson on 27 Jun 2017
Hi Cache,
Yes there is. Since you are multiplying each row of x by a constant,
Sigma = x.'*(repmat(A,1,n).*x) % A is column vector
% or
Sigma = x.'*(A.*x) % with latest versions of Matlab (implicit expansion)
The first line assumes that you have enough space for another matrix the same size as x. If not, and if the second line doesn't work there is always for-loop in-place computation of A.*[each column of x] if necessary.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!