MATLAB: Mean value of data with irregular intervals

datairregular intervalmean value

Hello,
I am trying to obtain average y value for a data set (x,y). However, interval between data points is not regular and mean(y) is off from the expected value. For example,
x = [1 1.1 1.2 1.3 2 3 4 5.1 5.2 5.3 5.4]; y = [0 0.1 0.2 0.3 1 2 1 0.3 0.2 0.1 0];
Because x,y are more densely lying in x = [0 1] and [5 6] intervals, y values in those intervals are weighted more if I take mean(y). Do you know how to avoid this and obtain y value in uniform intervals?
Thanks, Bobo

Best Answer

Why not just take a weighted mean?
This method ignores y(1) - you could change it to ignore y(end), or add info and inclue it.
totalweight = 0;
weightedsum = 0;
for i = 2:numel(x)
weight = x(i)-x(i-1);
weightedsum = weightedsum + weight*y(i);
totalweight = totalweight + weight;
end
meanvalue = weightedsum / totalweight;