MATLAB Answers

Calculate only diagonal elements of multidimensional array product

7 views (last 30 days)
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.


David Goodmanson
David Goodmanson on 28 Nov 2019
Hi Michael,
one way is
Ares = reshape(A.',1,M*M);
Bres = reshape(B,M*M,N);
Result = Ares*Bres;
although I have no idea where it stands speedwise.
Michael Werther
Michael Werther on 28 Nov 2019
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 on 2 Dec 2019
Hi Michael, your question was pretty clear since it's only a single sum instead of a double one, so my comment is toast.

Sign in to comment.

Accepted Answer

Matt J
Matt J on 2 Dec 2019
Edited: Matt J on 2 Dec 2019
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,

  1 Comment

Michael Werther
Michael Werther on 13 Dec 2019
Dear Matt,
thank your for your reply. This is indeed what I was looking for - never thought it could be that easy!

Sign in to comment.

More Answers (1)

Matt J
Matt J on 2 Dec 2019
Edited: Matt J on 2 Dec 2019
Since M is small, a for-loop would probably also be fine,
for i=1:M^2


Sign in to comment.

Sign in to answer this question.