I have a matrix of data, and I want to count the number of columns that match, and have some way to organize them by frequency. But I don't want to count the entire column, but consider the matrix divided into sections. For example, I want columns of length two with this matrix:

matrix->matrix split 1 + matrix split 2.

Then for each of these, I want to count the occurrences of matching columns. For example, in matrix split 2 there are two occurrences of {C,B}, two occurrences of {A,A}, and one occurrence of {C,B}. Then I want to change all the values by a rule. I need something like:

matrix split 2 -> enter image description here

matrix split 2 -> enter image description here by the rule that in the first row, c-> 0 and everything else -> 1, and in the second row B->0 and everything else -> 1.

I hope this is all clear. I am definitely at a loss for how to do this. Mathematica is quite frustrating for me at times.

  • $\begingroup$ You can use Take[] to extract rows, Transpose[] to turn columns into rows, and then Tally[] to count occurences in rows. $\endgroup$ Commented May 29, 2015 at 2:21

1 Answer 1


I'll leave it to you to figure out how to get a "slice" of you matrices, I'll use one from your OP for the example.

slice = {{c, a, c, b, a}, {b, a, b, c, a}};

With[{ts = Transpose@#}, 
   Transpose[{GatherBy[Transpose[{ts, Range@Length@ts}], First][[All, 
       All, 2]], Tally[ts][[All, 2]]}]] &@slice

MapThread[With[{s = #, c = #2}, Boole[# =!= c] & /@ s] &, {slice, {c, b}}]


{{{1, 3}, 2}, {{2, 5}, 2}, {{4}, 1}}

{{0, 1, 0, 1, 1}, {0, 1, 0, 1, 1}}


The road from frustration is paved with documentation...

In the future, please read the editing help, and post proper MMA code/list/etc. - readers are usually not inclined to manually type from images.


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.