MATLAB: Replace numbers in a matrix depending on the shape in which a group of numbers are located

imageimage processingMATLABmatrixmatrix arraymatrix manipulation

Hi community,
I have a matrix containing numbers 1 and 2, where numbers 2s are 'the background'. In this manner, in my matrix there are small groups of numbers 1s embedded in a lot of numbers 2. I need to do a 'cleaning step' of this matrix, looking for linear groups of only one column and several rows of numbers 1s, being able to convert them in numbers 2s. I would like to be able to choose which is the starting amount of numbers 1s in which the modification must be performed.
For example, considering this matrix:
[2 2 2 2 2 2 2 2 2 2;
2 1 1 2 1 2 1 2 1 2;
2 1 1 2 1 2 1 2 2 2;
2 2 2 2 1 2 1 2 1 2;
2 2 2 2 2 2 1 2 1 2;
2 2 2 2 2 2 2 2 2 2]
If I select as a threshold value 3, the intended output is to look for linear groups of 3 or more 1s, and convert them into number 2:
[2 2 2 2 2 2 2 2 2 2;
2 1 1 2 2 2 2 2 1 2;
2 1 1 2 2 2 2 2 2 2;
2 2 2 2 2 2 2 2 1 2;
2 2 2 2 2 2 2 2 1 2;
2 2 2 2 2 2 2 2 2 2]
Thank you very much for your collaboration!

Best Answer

out = 2 - A;
cc = bwconncomp(out);
z = cc.PixelIdxList;
n = cellfun(@numel,z) >= 3;
idx = z(n);
zz = cellfun(@(x)unique(diff(rem(x,cc.ImageSize(1)))),z,'un',0);
ii = idx(cellfun(@(x) numel(x) == 1,zz(n)));
out(cell2mat(ii(:))) = 0;
out(out == 0) = 2;
ADDED
threshold = 300;
out = 2 - A;
cc = bwconncomp(out);
for ii = 1:cc.NumObjects
jj = cc.PixelIdxList{ii};
if numel(jj) >= threshold...
&& numel( unique( ceil( jj/cc.ImageSize(1) ) ) ) <= 2
A(jj) = 2;
end
end