Calculate only diagonal elements of multidimensional array product

1 次查看(过去 30 天)
Hi everybody,
I have two arrays and , where M is small and N is large. What would be the fastest way to calculate for all l? I could do
sum(repmat(A.',[1,1,N]).*B,1), but since N is large this doesn't seem the best idea to me. Any help is appreciated.
Thanks
  3 个评论
Michael Werther
Michael Werther 2019-11-28
编辑:Michael Werther 2019-11-28
Dear David,
thank you for your prompt reply. In contrast to my first intention and although it is indeed faster, this is unfortunately not giving the desired result. Probably this was my fault, since I did not pose the question precisely. Actually I need to calculate for all l. I have specified this in the question.
David Goodmanson
David Goodmanson 2019-12-2
Hi Michael, your question was pretty clear since it's only a single sum instead of a double one, so my comment is toast.

请先登录,再进行评论。

采纳的回答

Matt J
Matt J 2019-12-2
编辑:Matt J 2019-12-2
Assuming your Matlab version is post-R2016b
reuslt = sum(B.*A.',1)
Otherwise, assuming your Matlab version is post-R2008
result = sum(bsxfun(@times, B,A.'),1)
And even if your Matlab version is really, really, really old, then there is still as a last resort,
At=A.';
C=diag(At(:))*reshape(B,[],N));
result=sum(reshape(C,M,M,N),1)
  1 个评论
Michael Werther
Michael Werther 2019-12-13
Dear Matt,
thank your for your reply. This is indeed what I was looking for - never thought it could be that easy!

请先登录,再进行评论。

更多回答(1 个)

Matt J
Matt J 2019-12-2
编辑:Matt J 2019-12-2
Since M is small, a for-loop would probably also be fine,
[j,k]=sub2ind([M,M],1:M.^2);
for i=1:M^2
B(j(i),k(i),:)=B(j(i),k(i),:).*A(k(i),j(i));
end
result=sum(B,1);

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by