You've got me thinking about linear algebra, and I happened to doodle this up when I ought to have been doing work:

package QDMatrix; use v5.36; sub new($class, $n_minor, $values) { if (ref $values->[0]) { $#{$values->[$_]} == $n_minor or die "Irregular column len in +matrix: $#{$values->[$_]} != $n_minor" for 0..$#$values; $values= [ @$values ]; } else { @$values % $n_minor == 0 or die "Un-rectangular number of values in data: ".scalar( +@$values)." / $n_minor = ".(@$values/$n_minor); $values= [ map [ @{$values}[$_*$n_minor .. ($_+1)*$n_minor-1] ], 0 .. int($#$values/$n_minor) ] } bless $values, $class; } sub flatten($self) { map @$_, @$self } sub clone($self) { bless [ map [ @$_ ], @$self ], ref $self; } sub dims($self) { scalar @$self, scalar @{$self->[0]} } sub major($self, $i) { @{$self->[$i]} } sub minor($self, $i) { map $_->[$i], @$self } sub mul($self, $m2) { my ($maj, $min)= $self->dims; my ($m2_maj, $m2_min)= $m2->dims; $min == $m2_maj or die "Incompatible matrix sizes: ($maj,$min) X ($m2_maj,$m2_ +min)"; my @ret; for my $i (0 .. $maj-1) { for my $j (0 .. $m2_min-1) { my $sum= 0; $sum += $self->[$i][$_] * $m2->[$_][$j] for 0 .. $min-1; $ret[$i][$j]= $sum; } } bless \@ret, ref $self; } sub transpose($self) { bless [ map [ $self->minor($_) ], 0 .. $#{$self->[0]} ], ref $self +; } my $identity= QDMatrix->new(3, [ 1,0,0, 0,1,0, 0,0,1 ]); my $x= QDMatrix->new(3, [ 4,5,1 ])->mul($identity->mul(QDMatrix->new(3 +, [ 1,0,0, 0,1,0, 2,0,1 ]))); use DDP; p $x;

In reply to Re^3: Translating python math to Perl by NERDVANA
in thread Translating python math to Perl by cavac

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.