Got it!
new_img = zeros(size(img)+2);
new_img(2:end-1,2:end-1) = double(img);
% Image boundary coordinates without first/last row/column
inner_coord = [2 2; size(new_img,1)-1 size(new_img,2)-1];
% 9x2 matrix with 1 row for the relative shift to reach neighbors
[d2, d1] = meshgrid(-1:1, -1:1);
d = [d1(:) d2(:)];
% Cell array to store all 9 shifted images
temp = {};
for i = 1:size(d,1)
% x-indices of the submatrix when shifted by d(i,1)
coord_x = (inner_coord(1,1):inner_coord(2,1)) + d(i,1);
% y-indices of the submatrix when shifted by d(i,2)
coord_y = (inner_coord(1,2):inner_coord(2,2)) + d(i,2);
% image matrices resulting from shift by d(i,)
temp{i} = reshape(new_img(coord_x, coord_y), 1, []);
end
% Column-wise bind all 9 shifted images
M_feat = vertcat(temp{:}).';