Trying to create the AS3 equivalent of both median and averaging filters.
An averaging filter would simply be getting the average values of an array\'s contents.
Assuming you have an Array
(or Vector) of numbers:
Use sort()
with Array.NUMERIC
:
numbers.sort(Array.NUMERIC);
Use slice()
to copy a sub-set of the sorted array:
var middleIndex:int = numbers.length / 2;
var middleNumbers:Array = numbers.slice(middleIndex - 2, middleIndex + 2);
Write a function which uses a for
loop to iterate over the elements and sum them, then divide the sum by the array's length:
function average(numbers:Array):Number {
var sum:Number = 0;
for each(var n:Number in numbers){
sum += n;
}
return sum / numbers.length;
}
For the median, you want the middle number if the length is odd, or the average of the two middle numbers if the length is even:
function median(numbers:Array):Number {
var middle:Number = numbers.length / 2;
if(middle is int){
return numbers[middle];
}else{
return (numbers[int(middle)] + numbers[int(middle) + 1]) / 2;
}
}