# How to count column occurrences in a matrix?

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:

-> + .

Then for each of these, I want to count the occurrences of matching columns. For example, in 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:

->

-> 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.

• You can use Take[] to extract rows, Transpose[] to turn columns into rows, and then Tally[] to count occurences in rows. – J. M.'s technical difficulties May 29 '15 at 2:21

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.