I have some code that works fine but I currently have the same code three times, I'd like to refactor to a single function that is called from three places instead.
The current code has access to a List(Of Sample) where a Sample object contains a sample reading for three axes x, y & z . The code calculates the mean average of the samples and subtracts this from each sample before then calculating the RMS (root mean square) of a given axis from the sample List.
This code is executed separately for each axis e.g. just the X axis, as follows
vb Code:
Public Function CalcRmsX() As Double Dim Rms As Double = 0 Dim Mean As Double = 0 Dim Count As UInteger = _samples.Count() If Count > 0 Then Mean = _samples.Sum(Function(smpl) smpl.X) 'Take the sum of each sample Mean = Mean / Count 'Divide for the mean For Each smpl As Sample In _samples 'Subtract the mean from each sample to remove any bias smpl.X = smpl.X - Mean Next Rms = _samples.Sum(Function(smpl) smpl.X ^ 2) 'Take the sum of the square of each sample Rms = Rms / Count 'Divide for the mean square Rms = Math.Sqrt(Rms) 'Take the sqare root of the mean square End If Return Rms End Function
I'd like to end up with a function where a function call would instead look as follows
[HIGHLIGHT=vb]
Dim RmsX As Double = CalcRms(X) 'Refactor to pass the axis as an argument like this
Dim RmsX As Double = CalcXRms() 'Rather than calling a different function per axis like this
[HIGHLIGHT=vb]
But my VB.NET foo is not strong enough to know how to change the function to make a function argument (the axis) select an object member (the Sample member). Is this possible?
Thanks, T




Reply With Quote