MATLAB: How to perform matrix operation efficiently

matrix function

I have an array X(n,m) where m<<n and n can be very large. First, I want to create a 3-d array of dimension (m,m,n) such that each mxm matrix in the nth location is the outer product of the n-th m-dimensional row in the original X- array.
Then I want to form a weighted sum all the mxm arrays where the weights are the elements of another n-dimensional array, Y(n).
result=zeros(m);
for i=1:n
result = result + Y(i) * X(i,:)' * X(i,:);
end
I could do this in the loop, but I think it would be slow when n is very large, compared to if there were a way to do all this with some matrix operation functions in MATLAB.

Best Answer

If m is much smaller than n and assuming Y is a column vector, try this:
R = zeros(m);
TX = X';
for ix = 1:m
R(:,ix) = TX*(X(:,ix).*Y); % <-- R is 'result'
end