How can I extract only the diagonal elements of a matrix product without computing the whole product matrix?
4 ビュー (過去 30 日間)
古いコメントを表示
Ranjan Sonalkar
2014 年 6 月 12 日
コメント済み: VICTOR MIRASIERRA CALLEJA
2023 年 1 月 12 日
I have nxk matrix (A) and a kxk (B) matrix where n>>k. I want the diagonal terms of A*B*A' in a n-vector. It would be wasteful to compute the whole A*B*A' and then extract the diagonal vector. What is the easy and efficient way to do this?
Thanks.
2 件のコメント
採用された回答
David Young
2014 年 6 月 12 日
編集済み: David Young
2014 年 6 月 12 日
You could use
sum((a * b) .* a, 2)
A check:
a = rand(1000, 10);
b = rand(10);
max(abs(diag(a*b*a.') - sum((a*b).*a,2)))
And yes, it's quicker:
f1 = @() diag(a * b * a.');
f2 = @() sum((a*b).*a, 2);
timeit(f1)
ans = 0.0104
timeit(f2)
ans = 1.2795e-04
[Edit: my example originally had n < k, which only gave a modest speedup. For n >> k, as required, the speedup is much greater, as expected.]
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Operating on Diagonal Matrices についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!