summaryrefslogtreecommitdiff
path: root/lib/PDF/Builder/Matrix.pm
blob: e97a2ad5b01fd93aebab3109be63f94413e7c914 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#=======================================================================
#
#   PDF::Builder::Matrix
#   Original Copyright 1995-96 Ulrich Pfeifer.
#   modified by Alfred Reibenschuh <areibens@cpan.org> for PDF::API2
#   rewritten by Steve Simms <steve@deefs.net> and licensed under the same 
#      terms as the rest of PDF::API2
#
#=======================================================================
package PDF::Builder::Matrix;

use strict;
use warnings;
use Carp;

our $VERSION = '3.026'; # VERSION
our $LAST_UPDATE = '3.020'; # manually update whenever code is changed

=head1 NAME

PDF::Builder::Matrix - matrix operations library

=cut

sub new {
    my $type = shift();

    my $self = [];
    my $col_count = scalar(@{$_[0]});
    foreach my $row (@_) {
        unless (scalar(@$row) == $col_count) {
	    carp 'Inconsistent column count in matrix';
	    return;
        }
        push(@{$self}, [@$row]);
    }

    return bless($self, $type);
}

# internal routine
sub transpose {
    my $self = shift();

    my @result;
    my $m;

    for my $col (@{$self->[0]}) {
        push @result, [];
    }
    for my $row (@$self) {
        $m = 0;
        for my $col (@$row) {
            push @{$result[$m++]}, $col;
        }
    }

    return PDF::Builder::Matrix->new(@result);
}

# internal routine
sub vector_product {
    my ($a, $b) = @_;
    my $result = 0;

    for my $i (0 .. $#{$a}) {
        $result += $a->[$i] * $b->[$i];
    }

    return $result;
}

# used by Content.pm
sub multiply {
    my $self  = shift();
    my $other = shift->transpose();

    my @result;

    unless ($#{$self->[0]} == $#{$other->[0]}) {
	carp 'Mismatched dimensions in matrix multiplication';
	return;
    }
    for my $row (@$self) {
        my $result_col = [];
        for my $col (@$other) {
            push @$result_col, vector_product($row,$col);
        }
        push @result, $result_col;
    }

    return PDF::Builder::Matrix->new(@result);
}

1;