I have an n by n matrix and would like to count the number of sub-matrices that is equal to a given matrix. Here is my code: DWBCL creates a matrix with elements a1, a2 and c2 in it and DWBCH with b1, b2 and c2.

DWBCL[a1_, a2_, c2_, n_] := Module[{M0, M1, M2, M3, M4, Mfinal},
  M0 = IdentityMatrix[n]*c2;
  M1 = ConstantArray[a1, {n, n}];
  M2 = ConstantArray[a2, {n, n}];
  M3 = UpperTriangularize[M1, 1];
  M4 = LowerTriangularize[M2, -1];
  Mfinal = M0 + M3 + M4]
DWBCH[b1_, b2_, c2_, n_] := Reverse[DWBCL[b2, b1, c2, n]]

Now, I want to check the total number of sub-matrix $S_a$ in DWBCL or DWBCH where $S_a$ is;

Sa = {{b1,c2},{c2,b2}}

For example, if I have

$$ \begin{pmatrix} b1 & b1 & b1 & b1 & b1 & c2\\ b1 & b1 & b1 & b1 & c2 & b2\\ b1 & b1 & b1 & c2 & b2 & b2\\ b1 & b1 & c2 & b2 & b2 & b2\\ b1 & c2 & b2 & b2 & b2 & b2\\ c2 & b2 & b2 & b2 & b2 & b2\\ \end{pmatrix} $$

and $ S_a= \begin{pmatrix} b1 & c2\\ c2 & b2\\ \end{pmatrix}$

then I want to I want to get 5 because there are 5 such blocks along the anti-diagonal.

After the counting, I want to update one of $S_a$ to $S_b$;

Sb = {{c2,c1},{a2,c2}}

I tried to use a loop structure to go through every element and use the if statement to check adjacent entries, but I wasn't sure how to do this in Mathematica.

Any suggestion will be appreciated.

  • $\begingroup$ In general the replacement is ill-defined. In a one-dimensional case, imagine DWBCL = {1, 1, 1}, Sa = {1, 1}, and Sb = {1, 2}. Should the result be {1, 2, 2} or {1, 1, 2}? In your example the ambiguity would be the elements on the diagonal, should they be c1 or a1? $\endgroup$ Commented Apr 1, 2015 at 13:52
  • $\begingroup$ Thank you! The counting works now! For the replacement, what I want to do is to replace one of Sa to Sb, and I want the position of Sa to be replaced to be chosen according to a random number generator. So using your 1D example, the result will be either {1, 2, 2} or {1, 1, 2} depending on the output of the random number generator. If the result is {1, 1, 2}, then I want to replace Sa once again, obtaining {1, 2, 2}. I am not sure what you mean that diagonal elements should be c1 or a1. Do you mean the diagonal of Sb? $\endgroup$
    – user27430
    Commented Apr 4, 2015 at 11:15

1 Answer 1


First we'll define our matrices. Using your definitions we can make a matrix m:

m = DWBCH[b1, b2, c2, 6]

sA is defined like so:

sA = {{b1, c2}, {c2, b2}}

(not Sa, since Mathematica capitalizes all it's functions we should generally use lowercase variables to avoid collisions.)

We can use Partition to split apart the matrix into sA-sized subarrays in steps of 1; then use Count to, uh, count how many instances match sA:

Count[Partition[m, Dimensions[sA], 1], sA, {2}]
(* 5 *)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.