MATLAB: Replace elements of a matrix by a smaller matrix which contains circular shaped values margins

circular shapeefficiencyreplace matrix values

Hello,
I'm having problems to efficiently replace some values of a result matrix.
The process is taking place ~50k times, so its very time intensive (result matrix: m,n > 1000).
Each time a much smaller matrix replaces a corresponding area in the result matrix.
The problem is, that the values in the small matrix form "the shape of a circle" and represent the presence of an attribute.
Like this:
A = result matrix (in reality: much bigger):
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 = small matrix (in reality: more elements in matrix, so that the value margins form the shape of a circle):
0 0 0 0
0 5 5 0
0 5 5 0
0 0 0 0
By performing "A(1:4, 1:4) = B" I get the result C:
0 0 0 0 1
0 5 5 0 1
0 5 5 0 1
0 0 0 0 1
1 1 1 1 1
I want the result:
1 1 1 1 1
1 5 5 1 1
1 5 5 1 1
1 1 1 1 1
1 1 1 1 1
I managed to get the result by first deleting the specific area of the result to "0" (only the ones that are not "0" in the small matrix "B") and then adding only the values of the small matrix that are not "0" by using two for-loops element-wise (50k times).
Unfortunately this takes very long….
Is there a more efficient way to do so?
Thank you very much in advance!

Best Answer

C = A;
sB = size(B);
idx = {1+(1:sB(1)),1+(1:sB(2))}; % adjust offset 1 and 1 if B to be moved at other place
C(idx{:}) = B
or depends on desired result
C(idx{:})= max(C(idx{:}), B)
Related Question