MATLAB: Replacing for loop with more efficient code

for loopvectorization

Hi, given symmetric matrices für i=1,…,m, positiv definite and symmetric and ,
I want to compute with .
I solved this with the following for loop:
for i=1:m
M_row=X*A(:,(i-1)*n+1:i*n)*inv_S;
for j=i:m %since M is symmetric
M(i,j)=trace(M_row*A(:,(j-1)*n+1:j*n));
end
end
Is there a more efficient way to solve this in matlab? with vectorization?

Best Answer

% Generate test matrices
m = 5;
n = 10;
S = rand(n,n);
S = 0.5*(S + S.');
X = rand(n,n);
X = 0.5*(X + X.');
A = zeros(n,n,m);
for k=1:m
Ak = rand(n,n);
Ak = 0.5*(Ak + Ak.');
A(:,:,k) = Ak;
end
AA = reshape(A,[n n m]);
M = zeros(m,m);
for i=1:m
Ti = S\(AA(:,:,i)*X);
M(i,:) = Ti(:).'*reshape(AA(:,:,:),[],m);
end