7
$\begingroup$

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.

I made up this code:

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?

$\endgroup$

4 Answers 4

7
$\begingroup$

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[]]]]]] :=
   rzvecs[accum, ll[head, tail]];

rzvecs[accum_, ll[head_?zeroVectorQ, ll[_?zeroVectorQ, tail_]]] :=
   rzvecs[ll[ll[accum, head], head], tail];

rzvecs[accum_, ll[head_, tail_]] := rzvecs[ll[accum, head], tail];

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.

$\endgroup$
7
  • $\begingroup$ +1, grrreat. I went on the smartless, easily compilable, procedulal road. I really like this one $\endgroup$
    – Rojo
    Feb 5, 2013 at 16:31
  • $\begingroup$ @Rojo Thanks. I tried to keep the solution essentially rule-based, that's why I went down this road. $\endgroup$ Feb 5, 2013 at 16:35
  • $\begingroup$ Should the following return {{0, 0}, {0, 0}, {0, 1}} ? m = {{0, 0}, {0, 0}, {0, 0}, {0, 1}}; $\endgroup$
    – halmir
    Feb 5, 2013 at 17:55
  • $\begingroup$ @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. $\endgroup$ Feb 5, 2013 at 18:02
  • $\begingroup$ @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}; $\endgroup$
    – halmir
    Feb 5, 2013 at 18:08
7
$\begingroup$

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];
$\endgroup$
17
  • $\begingroup$ 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. $\endgroup$ Feb 5, 2013 at 16:32
  • $\begingroup$ ...What's the n? $\endgroup$
    – Rojo
    Feb 5, 2013 at 16:33
  • $\begingroup$ @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. $\endgroup$
    – rm -rf
    Feb 5, 2013 at 16:33
  • $\begingroup$ @LeonidShifrin Yes, yes, I know... but, I'll gloat while I still can :D $\endgroup$
    – rm -rf
    Feb 5, 2013 at 16:34
  • $\begingroup$ How is z used? $\endgroup$ Feb 5, 2013 at 16:36
6
$\begingroup$

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;
$\endgroup$
3
  • $\begingroup$ +1, nice idea, and also seems to be the fastest so far. $\endgroup$ Feb 5, 2013 at 17:47
  • $\begingroup$ Great one Simon +1 $\endgroup$
    – Rojo
    Feb 5, 2013 at 17:52
  • $\begingroup$ Super clever, deserves more +1... $\endgroup$
    – ciao
    Mar 31, 2014 at 4:23
5
$\begingroup$
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]]
   ]]
$\endgroup$
1
  • $\begingroup$ It's good code, +1. $\endgroup$ Feb 5, 2013 at 17:02

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.