Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a solution (similar to what was done <a href="https://stackoverflow.com/questions/1745299/multiply-a-3d-matrix-with-a-2d-matrix/1745587#1745587">here</a>) that computes the result in a single matrix-multiplication operation, although it involves heavy manipulation of the matrices to put them into desired shape. I then compare it to the simple for-loop computation (which I admit is a lot more readable)</p> <pre><code>%# 3D matrices A = rand(4,2,3); B = rand(2,5,3); [m n p] = size(A); [n q p] = size(B); %# single matrix-multiplication operation (computes more products than needed) AA = reshape(permute(A,[2 1 3]), [n m*p])'; %'# cat(1,A(:,:,1),...,A(:,:,p)) BB = reshape(B, [n q*p]); %# cat(2,B(:,:,1),...,B(:,:,p)) CC = AA * BB; [mp qp] = size(CC); %# only keep "blocks" on the diagonal yy = repmat(1:qp, [m 1]); xx = bsxfun(@plus, repmat(1:m,[1 q])', 0:m:mp-1); %' idx = sub2ind(size(CC), xx(:), yy(:)); CC = reshape(CC(idx), [m q p]); %# compare against FOR-LOOP solution C = zeros(m,q,p); for i=1:p C(:,:,i) = A(:,:,i) * B(:,:,i); end isequal(C,CC) </code></pre> <p>Note that the above is performing more multiplications than needed, but sometimes <a href="http://undocumentedmatlab.com/blog/matrix-processing-performance/" rel="nofollow noreferrer"><em>"Anyone who adds, detracts (from execution time)"</em></a>. Sadly this is not the case, as the FOR-loop is much faster here :)</p> <p>My point was to show that vectorization is not easy, and that loop-based solutions are not always bad...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload