# Performance: Collapsing repeated contiguous rows & cols from a matrix

In this answer I needed to remove contiguous zero-valued cols and rows from a matrix, leaving only two of them in place, no matter what the original number was.

m = RandomVariate[BinomialDistribution[1, 10^-3], {400, 400}];
rule = {h__, {0 ..}, w : {0 ..}, {0 ..}, t__} -> {h, w, w, t};
mClean = Transpose[Transpose[m //. rule] //. rule];
Dimensions@mClean


But it is way too slow.
I'm pretty sure this code can be enhanced. Any better ideas?

### Linked lists - based solution

The real reason for the slowdown seems to be the same as usual for ReplaceRepeated - multiple copying of large arrays. I can offer a solution which would still be rule-based, but uses linked lists to avoid the mentioned slowdown. Here are auxiliary functions:

zeroVectorQ[x_] := VectorQ[x, IntegerQ] && Total[Unitize[x]] == 0;

toLinkedList[l_List] := Fold[ll[#2, #1] &, ll[], Reverse[l]]

ClearAll[rzvecs];
rzvecs[mat_List] :=  rzvecs[ll[First@#, ll[]], Last@#] &@toLinkedList[mat];

rzvecs[accum_, rest : (ll[] | ll[_, ll[_, ll[]]])] :=
List @@ Flatten[ll[accum, rest], Infinity, ll];

rzvecs[accum_, ll[head_?zeroVectorQ, ll[_?zeroVectorQ, tail : ll[_?zeroVectorQ, Except[ll[]]]]]] :=



Now the main function:

removeZeroVectors[mat_] := Nest[Transpose[rzvecs[#]] &, mat, 2]


### Benchmarks

Now the benchmarks:

m = RandomVariate[BinomialDistribution[1, 10^-3], {600, 600}];
(res = removeZeroVectors[m]); // AbsoluteTiming
(res1 = Transpose[Transpose[m //. rule] //. rule]); // AbsoluteTiming
res == res1

(*
{0.046875, Null}
{3.715820, Null}
True
*)


### Remarks

I have been promoting the uses of linked lists for some time now. In my opinion, in Mathematica they allow one to stay of the higher level of abstraction while achieving very decent (for the top-level code) performance. They also allow one to avoid many non-obvious performance-tuning tricks which take time to come up with, and even more time to understand for others. The algorithms expressed with linked lists are usually rather straight-forward and can be directly read off from the code.

• +1, grrreat. I went on the smartless, easily compilable, procedulal road. I really like this one
– Rojo
Commented Feb 5, 2013 at 16:31
• @Rojo Thanks. I tried to keep the solution essentially rule-based, that's why I went down this road. Commented Feb 5, 2013 at 16:35
• Should the following return {{0, 0}, {0, 0}, {0, 1}} ? m = {{0, 0}, {0, 0}, {0, 0}, {0, 1}}; Commented Feb 5, 2013 at 17:55
• @halmir No, it should not - the first and last columns are always kept and do not participate in the comparison. In a sense, the OP's original rule serves as a very clear spec. Commented Feb 5, 2013 at 18:02
• @LeonidShifrin I see. But OP's description sounds like it should. Probably, OP's rule need to be fixed like the following:rule = {h___, {0 ..}, w : {0 ..}, {0 ..}, t___} -> {h, w, w, t}; Commented Feb 5, 2013 at 18:08

It's not often I get to say this, but this is faster than Leonid's!

Clear@rZeroVecs
rZeroVecs[mat_, n_] := (Take[#, Min[n, Length@#]] & /@ Split[mat]) ~Flatten~ 1


Here n is the number of consecutive zero columns you wish to keep (sort of a generalized version of the question). Use it as:

m2 = Nest[rZeroVecs[Transpose@#, 2] &, m, 2];

• I wasn't going to produce the fastest solution - otherwise I'd just use Compile. I produced the solution which still uses rules and is two orders of magnitude faster than the original. Commented Feb 5, 2013 at 16:32
• ...What's the n?
– Rojo
Commented Feb 5, 2013 at 16:33
• @Rojo The number of consecutive zero rows/columns you want to keep (I generalized the objective in the question). I forgot to add in the function call... will do now.
– rm -rf
Commented Feb 5, 2013 at 16:33
• @LeonidShifrin Yes, yes, I know... but, I'll gloat while I still can :D
– rm -rf
Commented Feb 5, 2013 at 16:34
• How is z used? Commented Feb 5, 2013 at 16:36

My contribution:

cleanrows[m_] :=
Delete[m, 1 + Position[ListConvolve[{1, 1, 1}, Total[Unitize@m, {2}], {3, 1}], 0]]

m2 = Transpose @ cleanrows @ Transpose @ cleanrows @ m;

• +1, nice idea, and also seems to be the fastest so far. Commented Feb 5, 2013 at 17:47
• Great one Simon +1
– Rojo
Commented Feb 5, 2013 at 17:52
• Super clever, deserves more +1...
– ciao
Commented Mar 31, 2014 at 4:23
cleanAllProc[m_] := Transpose@cleanRowsProc@Transpose@cleanRowsProc@m

cleanRowsProc[m_] :=
With[{ceroRow = ConstantArray[0, Last@Dimensions@m]},
Module[{counter = 0, tag},
Reap[
Scan[
(If[# === ceroRow , If[++counter > 2, Continue[Null, Scan]],
counter = 0]; Sow[#, tag]) &, m],
tag
][[-1, 1]]
]]

• It's good code, +1. Commented Feb 5, 2013 at 17:02