Math-Cephes
view release on metacpan or search on metacpan
lib/Math/Cephes/Matrix.pm view on Meta::CPAN
package Math::Cephes::Matrix;
use strict;
use warnings;
use vars qw(@EXPORT_OK $VERSION);
require Exporter;
*import = \&Exporter::import;
@EXPORT_OK = qw(mat);
$VERSION = '0.5308';
require Math::Cephes;
sub new {
my ($caller, $arr) = @_;
my $refer = ref($caller);
my $class = $refer || $caller;
die "Must supply data for the matrix"
unless ($refer or $arr);
unless ($refer) {
die "Please supply an array of arrays for the matrix data"
unless (ref($arr) eq 'ARRAY' and ref($arr->[0]) eq 'ARRAY');
my $n = scalar @$arr;
my $m = scalar @{$arr->[0]};
die "Matrices must be square" unless $m == $n;
}
my ($coef, $n);
if ($refer) {
$n = $caller->{n};
my $cdata = $caller->{coef};
foreach (@$cdata) {
push @$coef, [ @$_];
}
}
else {
($coef, $n) = ($arr, scalar @$arr);
}
bless { coef => $coef,
n => $n,
}, $class;
}
sub mat {
return Math::Cephes::Matrix->new(shift);
}
sub mat_to_vec {
my $self = shift;
my ($M, $n) = ($self->{coef}, $self->{n});
my $A = [];
for (my $i=0; $i<$n; $i++) {
for (my $j=0; $j<$n; $j++) {
my $index = $i*$n+$j;
$A->[$index] = $M->[$i]->[$j];
}
}
return $A;
}
sub vec_to_mat {
my ($self, $X) = @_;
my $n = $self->{n};
my $I = [];
for (my $i=0; $i<$n; $i++) {
for (my $j=0; $j<$n; $j++) {
my $index = $i*$n+$j;
$I->[$i]->[$j] = $X->[$index];
}
}
return $I;
}
sub check {
my ($self, $B) = @_;
my $na = $self->{n};
my $ref = ref($B);
if ($ref eq 'Math::Cephes::Matrix') {
die "Matrices must be of the same size"
unless $B->{n} == $na;
return $B->coef;
}
elsif ($ref eq 'ARRAY') {
my $nb = scalar @$B;
my $ref0 = ref($B->[0]);
if ($ref0 eq 'ARRAY') {
my $m = scalar @{$B->[0]};
die "Can only use square matrices" unless $m == $nb;
die "Can only use matrices of the same size"
unless $na == $nb;
return $B;
}
( run in 1.981 second using v1.01-cache-2.11-cpan-40ba7b3775d )