MATLAB: Placing Blocks of fixed size to random positions in a bigger matrix

block processingrandom

How do you place a smaller matrix(block) of fixed size in a bigger matrix at random positions?

Best Answer

M = zeros(5)
m = randi(4,3)
sM = size(M);
sm = size(m);
k=sM-sm+1;
iM = reshape(1:numel(M),sM(1),[]);
iw = iM(1:k(1),1:k(2));
im = bsxfun(@plus,(0:sm(1)-1).',0:sM(1):sM(1)*(sm(2)-1));
M(iw(randi(numel(m)))+im) = m