MATLAB: How to close the boundary of a surface already generated by filling the holes

image boundaryimage processingImage Processing ToolboxMATLABmatrix manipulation

from give matrix (attached), i am using following code to close the surface and to make a boundary but i am getting errors that indexing is out of bound.
m = zeros(28)
m = load('Matrix_Boundary_fills_3s_only.txt');
[rows, colms] = size(m);
mOut = m;
for row = 2 : rows
for colm = 1:colms
if m(row-1, colm) == 3
mOut(row, colm+1) = 3;
if m(row-1, colm) == 3 || m(row-1,colm+2) == 3
mOut(row, colm+1) = 3;
if m(row-1, colm + 1) == 3
mOut(row, colm+1) = 3;
% end
thanks for all cooperation in advance.

Best Answer

Is the data (circle) expected to be convex? If so the ultra-easy way is to just use bwconvhull() followed by bwboundaries(), poly2mask(), and bwperim() like the code below. If not, you'll have to follow my answer to your other question where I tell you how to connect each endpoint to the closest other endpoint.
% Get and display original data.
[numbers, strings, raw] = xlsread('matrix.xlsx');
m = uint8(numbers);
subplot(2, 2, 1);
imshow(m, [], 'InitialMagnification', 800);
axis('on', 'image');
title('Original Data', 'FontSize', 20);
% Get convex hull.
chImage = bwconvhull(m);
subplot(2, 2, 2);
imshow(chImage, [], 'InitialMagnification', 800);
axis('on', 'image');
boundary = bwboundaries(chImage);
boundary = boundary{1}; % Extract the outermost boundary from the cell.
x = boundary(:, 2);
y = boundary(:, 1);
title('Convex Hull', 'FontSize', 20);
% Show results.

subplot(2, 2, 3);
imshow(m, [], 'InitialMagnification', 800);
axis('on', 'image');
hold on;
plot(x, y, 'r.-', 'LineWidth', 2, 'MarkerSize', 15);
title('Original Data with Boundary Overlaid', 'FontSize', 20);
% Get the perimeter
[rows, columns] = size(m);
mask = poly2mask(x, y, rows, columns); % Create a solid mask.
% Get the perimeter only.
perimImage = bwperim(mask);
% Show results.
subplot(2, 2, 4);
imshow(perimImage, [], 'InitialMagnification', 800);
axis('on', 'image');
title('New, Convex Perimeter', 'FontSize', 20);
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
If you don't want the x,y coordinates and only want the matrix, you can skip calling bwboundaries() and just call bwperim() directly on the convex hull image.
perimImage = bwperim(chImage);