Matrix multiply slices of 3d Matricies

53 views (last 30 days)
Dan Ryan
Dan Ryan on 5 Feb 2013
Given two 3d matricies, A and B with
size(A) = (n, m, k)
size(B) = (m, p, k)
perform matrix multiplications on each slice obtained by fixing the last index, yielding a matrix C with
size(C) = (n, p, k).
To clarify, we would have
C(:, :, 1) = A(:, :, 1)*B(:, :, 1), ..., C(:, :, k) = A(:, :, k)*B(:, :, k).
I need to do this with gpuArrays in the most efficient manner possible.

Accepted Answer

Jill Reese
Jill Reese on 9 Sep 2013
If you have MATLAB R2013b, you can use the new gpuArray pagefun function like so:
C = pagefun(@mtimes, A, B);

More Answers (2)

James Tursa
James Tursa on 14 Feb 2013
Edited: James Tursa on 14 Feb 2013
If you are not restricted to gpuArrays you can do this:
C = mtimesx(A,B);
The MTIMESX function passes pointers to the slice data to BLAS library functions in the background, so it is pretty fast. You can find MTIMESX here:
MTIMESX is not yet multi-threaded across the third dimension (but an update is in the works). A nD matrix multiply multi-threaded on the third dimension called MMX can also be used:
C = MMX('mult', A, B);
MMX can be found here:
  1 Comment
Dan Ryan
Dan Ryan on 14 Feb 2013
great suggestion, I will keep an eye on this project

Sign in to comment.

Azzi Abdelmalek
Azzi Abdelmalek on 5 Feb 2013
Edited: Azzi Abdelmalek on 5 Feb 2013
for ii=1:k
Jill Reese
Jill Reese on 14 Feb 2013
Can you elaborate on the sizes of m, n , k, and p that you are interested in? It would be useful to know a ballpark number for the size of problem you want to solve. Do you have many small page sizes, a few large pages, or something else?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!