Put edges of a matrix to zero

array  = ArrayReshape[Range[5 7], {5, 7}];
Fold[ArrayPad, array, {-1, 1}] // MatrixForm // TeXForm 

$\left( \begin{array}{ccccccc} 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 9 & 10 & 11 & 12 & 13 & 0 \\ 0 & 16 & 17 & 18 & 19 & 20 & 0 \\ 0 & 23 & 24 & 25 & 26 & 27 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)$

Also

ArrayPad[ArrayPad[array, -1], 1] 
ArrayPad[array[[2 ;; -2, 2 ;; -2]], 1] 
array (1 - MorphologicalPerimeter[array]) 
MapAt[0 &, array, {{All, {1, -1}}, {{1, -1}, All}}] 
ReplacePart[array, {1 | Dimensions[array][[1]], _} | {_, 1 | Dimensions[array][[2]]} :> 0]

all give the same result.


m = 2000;
n = 1000;
mat = RandomReal[{-1, 1}, {m, n}];

First@RepeatedTiming[


  M = mat;
  M[[{1, -1}, All]] = 0.;
  M[[2 ;; -2, {1, -1}]] = 0.;


  ]

0.0039