replacing for loop with more efficient code

조회 수: 2 (최근 30일)
Lukas Müller
Lukas Müller 2019년 1월 10일
댓글: Anusha Sridharan 2019년 1월 11일
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?
  댓글 수: 2
Bruno Luong
Bruno Luong 2019년 1월 11일
OP wants to compute
M(i,j) = Trace(X * A(:,:,i) * inv(S) * A(:,:,j))
where A(:,:,i), X and S are n x n symmetric, matrices, S and X are definite positive. i=1,...m
His original code that needs to be optimized is
M = zeros(m,m);
inv_S = inv(S);
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
Anusha Sridharan
Anusha Sridharan 2019년 1월 11일
[Answers Dev] Restored Edits

댓글을 달려면 로그인하십시오.

채택된 답변

Bruno Luong
Bruno Luong 2019년 1월 10일
% 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
  댓글 수: 1
Bruno Luong
Bruno Luong 2019년 1월 11일
The loop can be replaced by vectorized code if you use this mtimesxmtimesx FEX
AA = reshape(A,[n n m]);
Ti = mtimesx(mtimesx(inv(S),AA),X);
M = reshape(Ti,[],m).' *reshape(AA(:,:,:),[],m)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Lukas Müller
Lukas Müller 2019년 1월 10일
Thanks for you fast answer. So I guess it doesnt work without at least one for loop. Still way better then before thanks a lot :)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by