How can I improve the speed of the following matrix multiplication?

2 views (last 30 days)
My problem is doing the following calculation. Suppose the size of the matrix is as follows:
Mat A: [100 X 500]
Mat B: [500 X 1]
Mat C: [500 X 200]
All matrices are not sparse. What I want to calculate is
for i = 1:n
D = A*(B.*C)
end
Here, (B.*C) creates a matrix having a size of [500 X 200]. The problem is elements of the Mat B are changed in every loop whereas Mat A and C have constant elements. I think the cpu time for this calculation can be drastically reduced by calculating Mat A and C outside of the for-loop first. (Now, a matrix multiplication between Mat A, B, C is done in every loop again and again even though Mat A and C are matrices having constant elements.) But I don't know what I should do.. Can you please help me?
The Matlab code is
A = rand(100, 500);
C = rand(500, 200);
n = 1000;
for i = 1:n
B = rand(500, 1);
D(:,:,i) = A*(B.*C);
end
  6 Comments
dpb
dpb on 26 Aug 2018
Anything from James is bound to be good; I've not use the mtimesx package, however, so I can't comment on it. I suspect whatever issues you have are those owing to installing and building the necessary libraries which may be somewhat challenging since the mex setup evolves with releases of Matlab and one has to rebuild the package to run it.
dpb
dpb on 26 Aug 2018
" elements of the Mat B are changed in every loop whereas Mat A and C have constant elements. I think the cpu time for this calculation can be drastically reduced by calculating Mat A and C outside of the for-loop first. (Now, a matrix multiplication between Mat A, B, C is done in every loop again and again even though Mat A and C are matrices having constant elements.)"
I don't see why you think it should matter that A, C are constant; when you change B then the products must be recomputed.

Sign in to comment.

Accepted Answer

Bruno Luong
Bruno Luong on 26 Aug 2018
Edited: Bruno Luong on 27 Aug 2018
AC = reshape(reshape(A,size(A,1),1,[]).*reshape(C.',1,size(C,2)[]),[],size(B,1));
for i = 1:n
reshape(AC*B,size(A,1),[]); % = A*(B.*C)
end
  14 Comments
Bruno Luong
Bruno Luong on 27 Aug 2018
Edited: Bruno Luong on 27 Aug 2018
Reshape virtually takes no time, as Walter and I told you. The extra time is I suspect memory accessing of much larger array, which cannot be cache. So even my code requires less arithmetic operations (about 1/3 less) it is slower. You can profile by separate RESHAPE and MTIMES to check what we told you. But I also found the extra CPU time is quite a bad surprise.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!