Function Repository Resource:

ArrayCrop

Source Notebook

Remove padding from an array

Contributed by: Ed Pegg Jr

ResourceFunction["ArrayCrop"][array]

removes rows or columns of zeros from the top, bottom, left or right of an array.

ResourceFunction["ArrayCrop"][array,pad]

removes rows or columns of pad from the top, bottom, left or right of an array.

Examples

Basic Examples (2) 

Remove the zero padding around an array:

In[1]:=
array = {{0, 0, 1}, {1, 1, 1}, {0, 1, 0}}; padded = CenterArray[array, {7, 7}];
ResourceFunction["ArrayCrop"][padded]
Out[1]=

Remove the zero padding around a more complicated array:

In[2]:=
array = Map[Sqrt, RandomInteger[{-4, 4}, {3, 4}]]; padded = PadLeft[PadRight[array, {4, 5}], {9, 7}];
ResourceFunction["ArrayCrop"][padded]
Out[2]=
In[3]:=
% === array
Out[3]=

Scope (3) 

Create a symbolic array and pad it with zeros:

In[4]:=
array = Array[C, {5, 4}];
padded = ArrayPad[array, {{4, 3}, {3, 4}}]
Out[4]=

Remove the zero padding:

In[5]:=
ResourceFunction["ArrayCrop"][padded]
Out[5]=

Create an array padded by xs:

In[6]:=
array = {{0, 0, 1}, {1, 1, 1}, {0, 1, 0}};
padded = CenterArray[array, {7, 7}, x]
Out[6]=

Remove the padding:

In[7]:=
ResourceFunction["ArrayCrop"][padded, x]
Out[7]=

Create a symbolic rank-3 array and pad it with zeros:

In[8]:=
array = Array[C, {5, 4, 3}];
Short[padded = ArrayPad[array, {{4, 3}, {3, 4}, {2, 3}}]]
Out[8]=

Remove the padding:

In[9]:=
ResourceFunction["ArrayCrop"][padded]
Out[9]=

Possible Issues (1) 

If everything is padding, nothing is removed:

In[10]:=
array = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; padded = CenterArray[array, {7, 7}];
ResourceFunction["ArrayCrop"][padded]
Out[11]=

Version History

  • 1.0.0 – 21 September 2021

Related Resources

License Information