Octave:使用trace()的效率?
假设我有两个 5000 x 1000 矩阵,A 和 B。八度计算是否会高效地计算 trace(A*B')
,即只需要 5000 个内积,而不是 5000*5000 个内积其中大部分不会被使用?
而且,如果 trace
的参数更复杂,即:trace(A*B' + C*D')
该怎么办?这会改变什么吗?
Suppose I have two 5000 x 1000 matrices, A and B. Will octave compute trace(A*B')
efficiently, i.e. in a way that only requires 5000 inner products as opposed to 5000*5000 inner products most of which will not be used?
And, what if the argument to trace
is more complicated, i.e.: trace(A*B' + C*D')
? Does that change anything?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
trace(A*B')
将在使用trace()
之前计算完整的矩阵乘积。更有效的方法是
sum(sum(A.*conj(B),2))
。内部总和计算结果矩阵的对角线。一种可能更有效的方法是通过 `sum((A.*conj(B))(:)) 在一步中完成两个求和。
trace(A*B' + C*D')
将通过sum((A.*conj(B) + C.*conj(D))(:)) 高效计算
。trace(A*B')
will compute the complete matrix product before usingtrace()
.A more efficient approach would be
sum(sum(A.*conj(B),2))
. The inner sum computes the diagonal of the resulting matrix.A probably even more efficient approach would be doing both sums in one step via `sum((A.*conj(B))(:)).
trace(A*B' + C*D')
would be computed efficiently bysum((A.*conj(B) + C.*conj(D))(:))
.不,将在调用trace() 之前评估产品。一种有效的实现方法是仅手动计算该矩阵乘法的对角项,然后将它们相加
sum(sum(diag(A) .* diag(B)));
对于第二个示例sum(sum(diag(A) .* diag(B) + diag(C) .* diag(D)))
请注意,您可以稍微缩短这两个表达式,并且可能会损失一些速度可读性和 Matlab 兼容性如下:
sum((diag(A) .* diag(B))(:));
No, the product will be evaluated before the call to trace(). One efficient implementation would be to manually compute only the diagonal terms of that matrix multiply and then sum them
sum(sum(diag(A) .* diag(B)));
for your second examplesum(sum(diag(A) .* diag(B) + diag(C) .* diag(D)))
Note that you can shorten both expressions slightly and possibly gain a bit of speed at the loss of readability and Matlab compatibility like so:
sum((diag(A) .* diag(B))(:));