One-Liner Solution
Use:
mat(imdilate(mat==2,strel('disk',2)))=2;
Result
mat =
1 1 2 2 2 1 1 1
1 2 2 2 2 2 1 1
2 2 2 2 2 2 2 3
2 2 2 2 2 2 2 2
1 2 2 2 2 2 2 3
1 1 2 2 2 2 1 1
Step By Step explanation
The solution for this problem is based on dilation operation on the the areas in which the matrix is equal to 2.
This can be done as follow:
%initializes the input matrix
mat = [1,1,1,1,1,1,1,1 ; 1,1,1,1,1,1,1,1; 1,1,2,2,2,1,1,3 ; 1,1,2,2,2,2,1,3; 1,1,1,1,2,1,1,3 ; 1,1,1,1,1,1,1,1];
%initilizes a mask which represents the reion which we want to exapand
roiMask = mat==2;
%perform expansion to this mask by imdilate function
dilatedRoi = imdilate(mat==2,strel('disk',2));
%assigns the new value into the original matrix
mat(dilatedRoi) = 2;
Notice that the dilation operation is characterized by a structuring element object, which is basically a binary matrix which defines the way to perform the expansion.
In my example, I used MATLAB's strel function, which generates the following:
strel('disk',2)
ans =
0 0 1 0 0
0 1 1 1 0
1 1 1 1 1
0 1 1 1 0
0 0 1 0 0
You may want to change the strel in order to fully control the desired expansion behavior.