How about this? I'm not going into details, but basically if you represent your matrices as two-dimensional arrays (here I'm actually using array references), it's pretty straightforward to do the job.
I've coded standard deviation from memory so you might do well to check up the formula elsewhere - my memory is that you divide by (n - 1) rather than n (and here, "@matrices" evaluated in a scalar context will be n - the number of tables you're performing statistics over).
I'm loading the tables from the __DATA__ segment; should be obvious how to modify it to use stdin, a collection of files, or whatever. Have assumed that all of your tables will say 1..9 and 1..6 in their row/column labels.
There's loads of stuff to say on numerical accuracy when calculating means, but if you're using Perl to do the job I assume you don't care too much - the accuracy problems arise on pretty odd data sets anyway and aren't likely to be a problem.
To understand all of the [ foo ] and $x->[][] stuff, I recommend that you read the Perl documentation on references.
Hope this helps.
#!/usr/bin/perl -w
use strict;
# Convert your data format to a 2-d array
sub to_matrix($) {
[ map [ split /,/ ], split /\n/, shift ]
}
# Convert a 2-d array to your data format
sub from_matrix($) {
join("\n", map join(",", @$_), @{$_[0]}) . "\n";
}
# Read in matrices
$/ = "\n\n";
my @matrices = map to_matrix($_), <DATA>;
# Compute mean/std.dev
my $mean = [ [ "mean" ] ];
my $standard_deviation = [ [ "standard deviation" ] ];
$mean->[0][$_] = $standard_deviation->[0][$_] = $_ for 1 .. 6;
$mean->[$_][0] = $standard_deviation->[$_][0] = $_ for 1 .. 9;
for my $row (1 .. 9) {
for my $column (1 .. 6) {
my $sum = 0;
my $sum_of_squares = 0;
for(@matrices) {
my $datum = $_->[$row][$column];
$sum += $datum;
$sum_of_squares += $datum * $datum;
}
$mean->[$row][$column] = $sum / @matrices;
$standard_deviation->[$row][$column] = sqrt(($sum_of_squares -
$sum * $sum / @matrices) / (@matrices - 1));
}
}
print from_matrix($mean), "\n", from_matrix($standard_deviation);
__DATA__
units,1,2,3,4,5,6
1,5,0,0,0,0,0
2,0,0,0,0,0,0
3,0,0,1,1,0,0
4,0,4,0,0,0,0
5,0,3,0,0,0,0
6,0,0,0,0,0,0
7,0,0,0,0,0,0
8,0,0,0,0,0,0
9,1,0,0,0,0,0
blah,1,2,3,4,5,6
1,6,0,0,0,0,0
2,0,0,0,0,0,0
3,0,0,1,1,0,0
4,0,4,0,0,0,0
5,0,3,0,0,0,0
6,0,0,0,0,0,0
7,0,0,0,0,0,0
8,0,0,0,0,0,0
9,1,0,0,0,0,3
foo,1,2,3,4,5,6
1,7,0,0,0,0,0
2,0,0,0,0,0,0
3,0,0,1,1,0,0
4,0,4,0,0,0,0
5,0,3,0,0,0,0
6,0,0,0,0,0,0
7,0,0,0,0,0,0
8,0,0,0,0,0,0
9,1,0,0,0,0,2
|