One possibility is to use repmat
to repeat the small matrix as many times as necessary:
C = repmat(A,size(B,1)/size(A,1),size(B,2)/size(A,2)).*B
Another possibility, which avoids repmat
: cut up the large matrix, arrange the pieces in the third and fourth dimensions, and use bsxfun
to do the multiplication:
[m n] = size(A);
[M N] = size(B);
T = permute(reshape(B,M,n,[]), [2 1 3]);
T = permute(reshape(T,n,m,[],size(T,3)),[2 1 3 4]);
C = cell2mat(squeeze(mat2cell(bsxfun(@times,T,A),m,n,ones(1,M/m),ones(1,N/n))));
(The two lines T = ...
do the cutting, and are due to A. Donda.)
The advantage of this approach is that, if memory is an issue, you can overwrite B
instead of defining T
, thus saving memory:
[m n] = size(A);
[M N] = size(B);
B = permute(reshape(B,M,n,[]),[2 1 3]);
B = permute(reshape(B,n,m,[],size(B,3)),[2 1 3 4]);
C = cell2mat(squeeze(mat2cell(bsxfun(@times,B,A),m,n,ones(1,M/m),ones(1,N/n))));