MATLAB: Moving average of unevenly spaced time data

irregular spaced data

Hello,
I have the following data, and need to average the signal data as per defined window size. Any help?
signal= [0.1 0.2 0.15 0.3]; % volt reading
time_signal = [3.5 5.5 6.5 10.5];% seconds after event, the time when signal was recorded
time_regular = [ *1 2 3 4* 5 6 7 8 *9 10 11 12 13*]; time in seconds
Window_size is 4, 4 and 5. I want to average the signal data that falls within first 4 seconds, then next 4 seconds and finally in next 5 seconds. I highlighted the window sizes in time_regular array.
The answer is 0.1, 0.175 and 0.3. The calculation is done as follows. In first 4 seconds there is only one signal data point that falls within first 4 seconds, therefore first value is 0.1. In next 4 seconds, there are two signal data points (0.2 and 0.15), therefore the average of these two points is 0.175. In next 5 seconds, there is only one signal data point (0.3), therefore the average is 0.3. I can do this using for loop, but I have 100s of window sizes and big data.
Any matlab function can do this trick?

Best Answer

t = randi([3 5],6,1); % your time intervals in seconds
n = cumsum(t);
s = rand(n(end),1);
s = s.*(s < .3); % your signal
ii = zeros(n(end),1);
ii(n - t + 1) = 1;
s(s == 0) = nan;
out = accumarray(cumsum(ii),s,[],@(x)mean(x,'omitnan'));