MATLAB: Matrix insert with a condition

matrix manipulation

can you help me insert m x n matrix into M x N matrix with a condition that is without zero.
starting location is (x,y)
M x N =
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
m x n =
0 2 2 0
2 2 2 2
0 2 2 0
(x,y) = (4,3)
M x N =
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 2 2 1 1 1 1
1 1 1 2 2 2 2 1 1 1
1 1 1 1 2 2 1 1 1 1

Best Answer

  • A = [1 1 1 1 1 1 1 1 1 1
    1 1 1 1 1 1 1 1 1 1
    1 1 1 1 1 1 1 1 1 1
    1 1 1 1 1 1 1 1 1 1
    1 1 1 1 1 1 1 1 1 1];
    B = [0 2 2 0
    2 2 2 2
    0 2 2 0];
    row = 3; col = 4;
    toinsert = B + ~B .* A(row:row+size(B, 1)-1, col:col+size(B, 2)-1);
    A(row:row+size(B, 1)-1, col:col+size(B, 2)-1) = toinsert