MATLAB: Weighted average of irregular intervals

coefficientintervalslatitudelongitudeweighted averageweighted mean

Hello,
I have a 555×5 matrix
C = [Lat Lon Bm Lower Upper]
Bm represents biomass data. Lower and Upper represent the lower and upper boundaries of the depths (cm) from which the data was procured. The depths in C are irregularly spaced. I want to split up my data into two different weighted depths: one at 5cm, and one at 25 cm. For the 5cm, I want to contain all weighted datapoints in C between 0 and 15cm. For the 25cm, I want to contain all weighted datapoints in C between 15cm and 30cm
I'm looking to calculate the coefficient for each datapoint that correlates to the weight of the datapoint within depth intervals.
With the coefficient for each datapoint, I can calculate the weight of the measurement within the two separate intervals I need
EX:
-77.63 162.87 0.66 0 10 -> COEFF = 1.0 -> weighted bm = 0.66
-37.78 175.32 61.967 0 20 -> COEFF = 0.75 -> weighted bm = 46.47
The first line's coefficient is 1 because 100% of the measurement is contained within the interval of 0 and 15cm The second line's coefficient is 0.75 because only 75% of the measurement is contained within the interval of 0 and 15cm
This example only shows what I would like to have for my 5cm comparison, but I would also like to do the same for the 30cm comparison with the intervals between 15 and 30cm.
After I have those coefficients, I would like to get the weighted average by multiplying the coefficient with the biomass measurement, and then create two new matrixes that contains latitude, longitude, and biomass (555×3), one for the 5cm depth, and one for the 25cm depth.
But for the most part, I am having trouble trying to come up with a loop or code that will accomplish the coefficient calculation. The rest is pretty straightforward I feel.
I have attached the data so you can have a better idea of what I'm working with I have no idea how I should approach this, so any help would be greatly appreciated!
Thank you,
Melissa

Best Answer

That is an interesting question. I will have to think of a way to make a cody problem out of it.
Here is how I would do it:
ranges = [0 15; 15 30; 30 45] %example data, col 1 is lower bound, col2 is upper bound
depths = [0 10; 0 15; 0 20; 5 10; 5 20; 20 30; 25 35; 5 40] %example data, lower/upper bounds
bm = [1 2 4 8 16 32 64 128]'; %example data
[dlow, rlow] = ndgrid(depths(:, 1), ranges(:, 1));
[dup, rup] = ndgrid(depths(:, 2), ranges(:, 2));
%we now have 2d matrices, where columns are ranges, rows are depths
inrange = (dlow < rup) & (dup > rlow);
coeffs = ((dup-dlow) - (dlow < rlow).*(rlow-dlow) - (dup>rup).*(dup-rup)) ./ (dup-dlow);
coeffs = coeffs .* inrange %calc when not in range is not valid
weightedbm = bsxfun(@times, bm, coeffs)