When your input data is sorted, I normally approach it like this:
# Compute average value for each group my ($prev_key, $cnt, $sum); foreach my $line (@data) { my ($key, $val) = parse_line($line); if (defined($prev_key) and $prev_key eq $key) { # Same group as last time, accumulate results ++$cnt, $sum += $val; } else { # New group starting. Print results from # previous group, then start new one. print "Group $prev_key avg=", $sum/$cnt, ", cnt=", $cnt, "\n"; $prev_key = $key, $cnt=1, $sum=$val; } } # Print results from last group. print "Group $prev_key avg=", $sum/$cnt, ", cnt=", $cnt, "\n";
And when you're data isn't sorted, you can always sort it first!
...roboticus
When your only tool is a hammer, all problems look like your thumb.
In reply to Re: Mean and standard deviation loop
by roboticus
in thread Mean and standard deviation loop
by SixShot
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |