If you already have the green path and just want to divide it in segments, I'd transform the coordinates of the green paths into a logical matrix. Then you can easily find the borders of the segment and display it as you want.
matrixSize = 600;
%Your green path 2 column vector
xPositions = greenPath(:,1);
yPositions = greenPath(:,2);
%Transform to logical matrix
greenPathMat = false(matrixSize);
idx = sub2ind([matrixSize, matrixSize], yPositions, xPositions);
greenPathMat(idx) = true;
%Get border in x and y direction
xBorders = diff(m,1,2);
yBorders = diff(m,1,1);
%Get Start and End
xStart = find(any(xBorders==1)) + 1;
xEnd = find(any(xBorders==-1));
yStart = find(any(yBorders==1,2)) + 1;
yEnd = find(any(yBorders==-1,2));
%Check if there are any values at matrix borders to add them to start/end
if any(m(:,1)); xStart = [1 xStart]; end
if any(m(:,end)); xEnd = [xEnd, matrixSize]; end
if any(m(1,:)); yStart = [1; yStart]; end
if any(m(end,:)); yEnd = [yEnd; matrixSize]; end
%Calc number of segments
nbSegments = length(xStart) * 2;
if length(xStart) == length(xEnd)
nbSegments = nbSegments - 1;
end
%Display path in black and white
imagesc(greenPathMat)
set(gca,"YDir","normal")
hold on
colormap gray
for ii = 1:floor(nbSegments/2)
%Vertical segments
plot(polyshape([xStart(ii) xStart(ii) xEnd(ii) xEnd(ii)],...
[yStart(ii) yEnd(ii) yEnd(ii) yStart(ii)]));
%Horizontal segments
plot(polyshape([xStart(ii) xStart(ii) xEnd(ii+1) xEnd(ii+1)],...
[yStart(ii+1) yEnd(ii) yEnd(ii) yStart(ii+1)]));
end
%If last segment is vertical
if length(xStart) == length(xEnd)
plot(polyshape([xStart(ii+1) xStart(ii+1) xEnd(ii+1) xEnd(ii+1)],...
[yStart(ii+1) yEnd(ii+1) yEnd(ii+1) yStart(ii+1)]));
end
If you plot them one by one it looks like this.
Is this what you want?