in reply to first stumbling steps in PDL

TIMTOWTDI, but PDL is not about explicit loops. Not how it works. Consider this vector:

pdl> p $v = pdl split '', '30373' [3 0 3 7 3]

Now then e.g. the cumulative sum or running total:

pdl> p cumusumover $v [3 3 6 13 16]

Not very useful, but I have a vague feeling that "cumulative maximum" would be handy if someone is looking at a forest. You could type

pdl> ?? cumulative

to investigate what's available. OK, then, consider "strictly lower triangular matrix" or whatever it's called in mathematics if non-zero members are all 1's:

pdl> p $SLTM [ [0 0 0 0 0] [1 0 0 0 0] [1 1 0 0 0] [1 1 1 0 0] [1 1 1 1 0] ]

Hm-m, looks interesting. Not sure about forestry, but what if it's multiplied by our vector?

pdl> p $SLTM * $v [ [0 0 0 0 0] [3 0 0 0 0] [3 0 0 0 0] [3 0 3 0 0] [3 0 3 7 0] ]

That's even more interesting! What could we use this result for? What about computing maximum over rows?

pdl> p maxover $SLTM * $v [0 3 3 3 7]

Now that's what I call interesting! Isn't it cumulative maximum of all elements before current for original vector? Let's check it without further ado:

pdl> p $v > maxover $SLTM * $v [1 0 0 1 0]

But wait, that's exactly the answer we were looking for -- what trees are seen if forest patch is looked at from the left!

And all the rest was just further expansion of investigation performed above.

Replies are listed 'Best First'.
Re^2: first stumbling steps in PDL
by etj (Priest) on Feb 02, 2024 at 19:12 UTC
    A slightly more concise way to get a lower triangular matrix of 1s:
    use PDL::LinearAlgebra; sub ltm { my ($size, $strictly) = @_; my $ltm = ones($size,$size)->tricpy(1); $strictly ? $ltm - identity($size) : $ltm; }

      Is there an advantage of using tricpy over mtri? At least mtri may be called without argument when an upper triangle is requested, while with tricpy it is always required.

      Greetings,
      -jo

      $gryYup$d0ylprbpriprrYpkJl2xyl~rzg??P~5lp2hyl0p$
        I'd say use whatever you find works! tricpy should clearly allow a default value of 0. Feel like making a PR? You'd have to make a PMCode function :-)
      Today it was bugging me that there is no tritosquare, to provide another way to make a lower-triangular matrix. Now there is, on git master and soonish to be released:
      pdl> p ones(10)->tritosquare [ [1 0 0 0] [1 1 0 0] [1 1 1 0] [1 1 1 1] ]

      A slightly different approach for a strictly lower triangular matrix:

      use PDL::LinearAlgebra::Real ... tricpy(zeros($size,$size), 0, my $sltm = ones($size, $size));

      Greetings,
      -jo

      $gryYup$d0ylprbpriprrYpkJl2xyl~rzg??P~5lp2hyl0p$
        Beautiful, with fewer operations!