Replacing a for loop with matrix multiplication

5 vues (au cours des 30 derniers jours)
Jessica Nadalin
Jessica Nadalin le 1 Fév 2021
Commenté : Bruno Luong le 1 Fév 2021
In the problem I have here, x is a 2x300 matrix and SIG is a 2x2 matrix.
What I'm looking for is a 1x300 vector, where the ith entry corresponds to x(:,i)'*inv(SIG)*x(:,i). I've written this out in a for loop below:
ans = zeros(1,size(x,2));
for i = 1:size(x,2)
ans(i) = x(:,i)'*inv(SIG)*x(:,i);
end
but I think there must be a way to make this more efficient with some sort of matrix multiplication--I just can't figure it out.
Any help appreciated!
  1 commentaire
Stephen23
Stephen23 le 1 Fév 2021
Modifié(e) : Stephen23 le 1 Fév 2021
Note that using inv is less efficient than using mldivide:

Connectez-vous pour commenter.

Réponse acceptée

James Tursa
James Tursa le 1 Fév 2021
Modifié(e) : James Tursa le 1 Fév 2021
result = sum(x.*(inv(SIG)*x));
or
result = sum(x.*(SIG\x));
  1 commentaire
Bruno Luong
Bruno Luong le 1 Fév 2021
In case complex data
result = sum(conj(x).*(SIG\x));

Connectez-vous pour commenter.

Plus de réponses (1)

J Chen
J Chen le 1 Fév 2021
Try x'*inv(SIG)*x. Matlab can directly handle vectors and matrices.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by