Function Repository Resource:

FindSubmatrix

Source Notebook

Find a submatrix in an array matching a pattern

Contributed by: Enrique Zeleny

ResourceFunction["FindSubmatrix"][array,pattern]

finds a submatrix in the array matching pattern.

Details

The dimensions of pattern must be the same as the submatrix.
type can be any of the following:
“Matrix"the submatrix that matches the pattern
"Positions"the position where the submatrix starts
"Image3D"an image showing the position of the submatrix
"Cuboids"cuboids at the position of the submatrices
"Raster"a raster showing the position of the submatrix

Examples

Basic Examples (4) 

Generate an array:

In[1]:=
(array = {{9, 2, 8, 4, 4, 9, 10, 5, 7, 6}, {3, 8, 8, 2, 8, 1, 5, 1, 10, 9}, {2, 10, 3, 7, 6, 1, 4, 8, 2, 5}, {4, 6, 8, 5, 3, 7, 3, 6, 7, 6}, {6, 10, 4, 9, 3, 5, 6, 8, 9, 6}, {4, 9, 7, 10, 8, 5, 6, 6, 6, 2}, {9, 7, 10, 3, 9, 5, 8, 9, 3, 8}, {9, 9, 10, 2, 4, 5, 1, 8, 7, 1}, {2, 3, 3, 3, 7, 7, 3, 7, 8, 8}, {2, 2, 7, 7, 3, 9, 2, 9, 1, 9}}) // MatrixForm
Out[1]=

Find a submatrix matching the pattern:

In[2]:=
ResourceFunction["FindSubmatrix"][array, {
  {3, _, 3},
  {_, 5, 6},
  {_, 5, 6}
 }]
Out[2]=

The position where the submatrix starts:

In[3]:=
ResourceFunction["FindSubmatrix"][array, {
  {3, _, 3},
  {_, 5, 6},
  {_, 5, 6}
 } , "Positions"]
Out[3]=

A raster showing the location of the submatrix:

In[4]:=
Graphics[ResourceFunction["FindSubmatrix"][
  array, {{3, _, 3}, {_, 5, 6}, {_, 5, 6}}, "Raster"], ImageSize -> Tiny]
Out[4]=

Scope (3) 

A tridimensional array:

In[5]:=
array2 = RandomInteger[{1, 10}, {10, 10, 10}];

Find a definite array:

In[6]:=
pat = Take[array2, {5, 8}, {5, 8}, {5, 8}]
Out[6]=
In[7]:=
ResourceFunction["FindSubmatrix"][array2, pat, "Positions"]
Out[7]=

Cuboids showing the location of submatrices:

In[8]:=
ResourceFunction["FindSubmatrix"][
  array2, {{{3, _}, {_, _}}, {{_, _}, {7, _}}}, "Cuboids"] // Graphics3D
Out[8]=

A 3D image showing the location of the submatrix:

In[9]:=
ResourceFunction[
 "FindSubmatrix"][array2, {{{3, _}, {_, _}}, {{_, _}, {7, _}}}, "Image3D"]
Out[9]=
In[10]:=
ResourceFunction["FindSubmatrix"][
  array2, {{{3, _}, {_, _}}, {{_, _}, {_, _}}}, "Raster"] // Graphics3D
Out[10]=

A SparseArray:

In[11]:=
s = SparseArray[
  Band[{1, 1}] -> {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}, {{9, 10}, {11, 12}}}]
Out[11]=
In[12]:=
MatrixForm[s]
Out[12]=
In[13]:=
ResourceFunction[
 "FindSubmatrix"][s, {{2, 0, _}, {4, 0, _}, {0, 5, 6}}]
Out[13]=

A 4–dimensional SparseArray:

In[14]:=
s = SparseArray@Table[RandomInteger[{1, 5}, 4] -> i, {i, 100}]
Out[14]=
In[15]:=
ResourceFunction[
 "FindSubmatrix"][array2, {{{3, _}, {_, _}}, {{_, _}, {3, _}}}]
Out[15]=

Publisher

Enrique Zeleny

Version History

  • 1.0.0 – 25 April 2022

Related Resources

License Information